JAVA 6: JDBC AND DATABASE APPLICATIONS. 5. Contents. 4. ResultSet. 22. 4.1. Update a ResultSet. 25. 4.2. Municipalities
POUL KLAUSEN
JAVA 6: JDBC AND DATABASE APPLICATIONS SOFTWARE DEVELOPMENT
Download free eBooks at bookboon.com 2
Java 6: JDBC and database applications: Software Development 1st edition © 2017 Poul Klausen & bookboon.com ISBN 978-87-403-1736-7 Peer review by Ove Thomsen, EA Dania
Download free eBooks at bookboon.com 3
Deloitte & Touche LLP and affiliated entities.
JAVA 6: JDBC AND DATABASE APPLICATIONS
Contents
CONTENTS Foreword
6
1 Introduction
8
About surrogate keys
10
2 JDBC
11
2.1 HelloJDBC
11
Exercise 1
14
3
Database operations
15
3.1
SQL statements
15
Exercise 2
20
360° thinking
.
360° thinking
.
360° thinking
.
Discover the truth at www.deloitte.ca/careers
© Deloitte & Touche LLP and affiliated entities.
Discover the truth at www.deloitte.ca/careers
© Deloitte & Touche LLP and affiliated entities.
Discoverfree theeBooks truth atatbookboon.com www.deloitte.ca/careers Download
Click on the ad to read more
4
Dis
JAVA 6: JDBC AND DATABASE APPLICATIONS
Contents
4 ResultSet
22
4.1
Update a ResultSet
25
4.2
Municipalities and zipcodes
29
Exercise 3
35
Problem 1
35
4.3
Stored procedures
37
5
Data types
40
6 Transactions
47
6.1
Bach updates
51
Exercise 4
53
7
The component JTable
54
7.1
The demo program
55
Problem 2
90
8
Files in databases
92
Exercise 5
96
9
DDL commands
97
10
Final examples
99
10.1 World
99
10.2 MyWines
107
Appendix A: Install MySQL
140
Appendix B
148
Download free eBooks at bookboon.com 5
JAVA 6: JDBC AND DATABASE APPLICATIONS
Foreword
FOREWORD This book is the sixth in a series of books on software development. The programming language is Java, and the language and its syntax and semantics fills obviously much, but the books have also largely focus on the process and how to develop good and robust applications. The subject of the current book is database applications, and how to write programs in Java that uses a database. In practice, programs that requiring many data transactions always uses databases, and the development of database applications is an important issue and necessary knowledge to work professionally as a software developer. In principle, it is simple, and a good piece of the road is just a question of accepting that you should write as shown in the book’s examples, but database programming requires knowledge of SQL, and the hardest part is actually to write SQL statements correctly. Therefore, the book has an appendix that provides a quick introduction to SQL and describes the most basic syntax. In addition to SQL it is a prerequisite, to try out the book’s examples and solve the book’s exercises, that the reader has a running database, and MySQL will be used. The book has an appendix that shows how to install MySQL. As the title says this series of books deals with software development, and the goal is to teach the reader how to develop applications in Java. It can be learned by reading about the subject and by studying complete sample programs, but most importantly by yourself to do it and write your own programs from scratch. Therefore, an important part of the books is exercises and problems, where the reader has to write programs that correspond to the substance being treated in the books. All books in the series is built around the same skeleton and will consist of text and examples and exercises and problems that are placed in the text where they naturally belongs. The difference between exercises and problems is that the exercises largely deals with repetitions of the substance that is presented in the text, and furthermore it is relatively accurately described what to do. Problems are in turn more loosely described, and are typically a little bigger and there is rarely any clear best solution. These are books to be read from start to finish, but the many code examples, including exercises and problems plays a central role, and it is important that the reader predict in detail studying the code to the many examples and also solves the exercises and problems or possibly just studying the recommended solutions.
Download free eBooks at bookboon.com 6
JAVA 6: JDBC AND DATABASE APPLICATIONS
Foreword
All books ends with one or two larger sample programs, which focus primarily is on process and an explanation of how the program is written. On the other hand appears the code only to a limited extent – if at all – and the reader should instead study the finished program code perhaps while testing the program. In addition to show the development of programs that are larger than the examples, which otherwise is presented, the aim of the concluding examples also is to show program examples from varying fields of application. Most books also ends with an appendix dealing with a subject that would not be treated in the books. It may be issues on the installation of software or other topics in computer technology, which are not about software development, but where it is necessary to have an introductory knowledge. If the reader already is familiar with the subject, the current appendix can be skipped. The programming language is, as mentioned Java, and besides the books use the following products: -- NetBeans as IDE for application development -- MySQL to the extent there is a need for a database server (from the book Java 6 onwards) -- GlassFish as a web server and application server (from the book Java 11 onwards) It is products that are free of charge and free to install, and there is even talk about products, where the installation is progressing all by itself and without major efforts and challenges. In addition, there are on the web detailed installation instructions for all the three products. The products are available on Windows and Linux, and it therefore plays no special role if you use Linux or Windows. All sample programs are developed and tested on machines running Linux. In fact, it plays no major role, as both Java and other products work in exactly the same way whether the platform is one or the other. Some places will be in the books where you could see that the platform is Linux, and this applies primarily commands that concerning the file system. Otherwise it has no meaning to the reader that the programs are developed on a Linux machine, and they can immediately also run under Windows unless a program refers to the file system where it may be necessary to change the name of a file. Finally a little about what the books are not. It is not “how to write” or for that matter reference manuals in Java, but it is as the title says books on software development. It is my hope that the reader when reading the books and through the many examples can find inspiration for how to write good programs, but also can be used as a source collection with a number of examples of solutions to concrete everyday programming problems that you regularly face as a software developer.
Download free eBooks at bookboon.com 7
JAVA 6: JDBC AND DATABASE APPLICATIONS
Introduction
1 INTRODUCTION Many applications need to use and maintain persistent data. In the preceding books, I have solved such tasks by using object serialization or plain text files, which indeed in some cases can be an excellent solution, but if there are large amounts of data with frequent updates, or data where multiple users must have access to the data, it is not a viable option. In these cases – and in practice, almost always – data are stored in databases. A database is a collection of files that contains related data of one or another business, but it’s a lot more because it is a software package that consists of programs that manages and maintains the database system’s databases. This software package is called a database management system, and by a database system is meant partly the management system as well as the databases that the system maintains. In this book I will address key concepts related to databases, but as the other of the books seen by a programmer, and thus especially what a programmer needs to know. The subject requires a specific database management system, and I will use MySQL. In fact, the system is not so important, but MySQL is available in an open source version that can be downloaded and installed for free. MySQL is today a powerful database system that supports all the services that one would expect from a good database management system, and besides MySQL is a widely used system in practice. In order to use MySQL from a Java program, you must at least install three products: 1. the database management system it self, that is the MySQL server 2. a program called MySQL Workbench, that the user can use to manage the system 3. a class library called JDBC, which makes it possible to write Java applications that uses databases The book’s appendix A shows how these products can be installed on the machine. The following is based on two assumptions: 1. that you have a running MySQL server installed with the above products (see appendix A for how to install the products) 2. you have an introductory knowledge of SQL and know the most common statements (see appendix B for an introduction).
Download free eBooks at bookboon.com 8
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Introduction IntroduCtIon
To show how to use databases from a Java program, you must also have a database. Open To show how to use databases from a Java program, you must also have a database. Open MySQL Workbench (see below). Perform then the command that is entered. You do this by MySQL Workbench (see below). Perform then the command that is entered. You do this by clicking on the third icon (lightning) in the toolbar. The result is the creation of a database clicking on the third icon (lightning) in the toolbar. The result is the creation of a database with the name padata. You may of course choose a different name if you wish, but it makes with the name padata. You may of course choose a different name if you wish, but it makes it easier to follow the book’s examples and exercises if you choose the same name, which I it easier to follow the book’s examples and exercises if you choose the same name, which I have used. So far, it is an empty database, but through the book I will create several tables have used. So far, it is an empty database, but through the book I will create several tables with data. with data. The folder to this book contains a SQL script called CreateHistorie.sql. Open this script in The folder to this book contains a SQL script called CreateHistorie.sql. Open this script in MySQL Workbench. The contents are as shown below: MySQL Workbench. The contents are as shown below:
use padata; drop table if exists history; create table history ( id int not null auto_increment primary key, # autogenerated surrogat key name varchar(50) not null, # the person's name title varchar(30), # the person's title birth int, # birth, start of reign, or equivalent death int, # death, end of reign, or equivalent country char(2), # the country the person comes from description text # a description );
Download free eBooks at bookboon.com 9 9
JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA
IntroduCtIon Introduction
script that that creates creates aa table table with with information information about about historical historical persons. persons. AA table table consists consists of of ItIt isis aa script rowsand andcolumns, columns,and andeach eachrow rowcontains containsdata data(information) (information)about aboutaaparticular particularperson. person.AAcolumn column rows has aa type type and and aa name. name. The The name name makes makes itit possible possible to to refer refer to to the the column column in in SQL SQL statements, statements, has while the the type type determines determines what what kind kind of of values values the the column column can can hold. hold. Taking Taking the the above above script, script, while indicating the the first first column, column, that that the the column column must must contain contain an an auto-generated auto-generated integer integer that that starts starts indicating with 11 and and increases increases by by 11 each each time time adding adding aa row row to to the the table. table. In In addition addition isis definied definied that that the the with column must must be be the the primary primary key, key, which which means means that that the the column’s column’s values values must must be be unique unique and and column thus can can serve serve to to identify identify each each row. row. The The next next two two columns columns are are of of the the type type varchar, varchar, indicating indicating thus that the the column column can can contain contain aa string, string, which which in in this this case case must must be be maximum maximum of, of, respectively respectively 50 50 that and 30 30 characters. characters. The The next next two two columns columns again again may may contain contain integers, integers, and and the the column column with with and the name name country country must must contain contain aa string string of of 22 characters. characters. Finally, Finally, the the last last column column can can contain contain the any text text (however, (however, maximum maximum 65535 65535 characters). characters). The The column column name name isis defined defined not not null, null, which which any means that that every every row row must must have have aa value value in in that that column. column. The The other other columns columns (except (except the the first first means that isis the the primary primary key) key) does does not not need need to to have have aa value, value, but but may may be be null. null. that The book’s book’s directory directory also also contains contains aa script script InsertHistory.sql InsertHistory.sql where where below below shows shows aa few few lines lines The use padata; insert into history ('Gorm den Gamle', insert into history ('Harald Blåtand', ...
(name, death, title, country) values 958, 'King', 'DK'); (name, birth, death, title, country) values 958, 987, 'King', 'DK');
IfIf you you opens opens the the script script in in MySQL MySQL Workbench Workbench and and executes executes it, it, the the script script adds adds 52 52 rows rows to to the table history, where the rows contains data about Danish kings. The following assumes the table history, where the rows contains data about Danish kings. The following assumes that that this this table table isis created, created, and and the the script script InsertHistory.sql InsertHistory.sql isis performed. performed.
ABOUT ABOUT SURROGATE SURROGATE KEYS KEYS When When you you have have to to create create (design) (design) aa database database table, table, you you must must choose choose one one or or more more columns columns that can be used as the primary key (above id ). This means that each row must have a that can be used as the primary key (above id ). This means that each row must have a unique unique value in this column or columns. Is it not possible, you can define a column, which value in this column or columns. Is it not possible, you can define a column, which then then isis assigned a unique value, and it is the case of the column id of the table history, when assigned a unique value, and it is the case of the column id of the table history, when the the value is automatically incremented by 1 each time you add a row to the table. This column value is automatically incremented by 1 each time you add a row to the table. This column can can therefore therefore be be used used as as the the primary primary key, key, and and itit isis called called aa surrogate surrogate key key corresponding corresponding to, to, that it is a replacement for another key column. Actually one should, if possible, avoid that it is a replacement for another key column. Actually one should, if possible, avoid surrogate surrogate keys keys as as they they expand expand the the table table with with data data that that does does not not tell tell anything, anything, and and in in this this case one might avoid the key as the Kings have unique names and thus the name could case one might avoid the key as the Kings have unique names and thus the name could be be used as the primary key. When I have nonetheless chosen a surrogate key, it is because used as the primary key. When I have nonetheless chosen a surrogate key, it is because aa string string –– aa column column of of the the type type varchar varchar –– not not always always isis aa good good candidate candidate for for aa primary primary key, key, first, it may be difficult to enter (you can misspell) and partly it is less effective than an first, it may be difficult to enter (you can misspell) and partly it is less effective than an int. int.
Download free eBooks at bookboon.com 10 10
JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA
JdBC JDBC
2 JDBC 2 JDBC JDBC is is aa family family of of classes classes that that implements implements an an interfaces interfaces defined defined in in the the JDBC JDBC API, API, and and JDBC which makes makes itit possible, possible, that that aa Java Java program program can can communicate communicate with with aa database database server. server. In In which relation to to the the Java Java program program the the API API has has the the necessary necessary types types as as interfaces interfaces and and classes classes defined defined relation in the the package package java.sql, java.sql, while while the the specific specific types types are are implemented implemented by by aa JDBC JDBC driver. driver. So So there there in has to to be be aa JDBC JDBC driver driver available available for for each each of of the the databases databases that that the the program program must must apply apply and and has often itit is is the the database database supplier supplier that that develops develops the the JDBC JDBC driver. driver. You You can can think think of of aa JDBC JDBC often driver as as aa layer layer between between the the database database and and the the Java Java program program that that ensures ensures that that the the program program driver can use use the the database database in in the the same same way, way, whether whether itit is is one one or or the the other other database database system. system. can
2.1 HELLOJDBC 2.1 HELLOJDBC Before II go go further further and and look look at at the the details details concerning concerning JDBC, JDBC, II will will look look at at an an example example to to Before show that that itit is is quite quite easy easy to to use use aa database database from from aa Java Java program. program. The The following following program program show reads the the rows rows in in the the table table history history and and prints prints them them on on the the screen: screen: reads package hellojdbc; import java.sql.*; public class HelloJDBC { public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234"); stmt = conn.createStatement(); ResultSet res = stmt.executeQuery("SELECT * FROM history"); while(res.next()) { String name = res.getString("name"); String title = res.getString("title"); int birth = res.getInt("birth"); int death = res.getInt("death"); String country = res.getString("country"); System.out.printf("%-25s%-10S%5d%5d %s\n", name, title, birth, death, country); } }
Download free eBooks at bookboon.com 11 11
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
catch(SQLException ex) { System.out.println(ex); } catch(Exception ex) { System.out.println(ex); } finally { try { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException ex) TMP{PRODUCTION System.out.println(ex); 6x4 } gl/rv/rv/baf } } }
JDBC JdBC
NY026057B
4
12/13/2013
ACCCTR00
PSTANKIE Bookboon Ad Creative
All rights reserved.
© 2013 Accenture.
Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon
Download free eBooks at bookboon.com 12 12
Click on the ad to read more
JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
JDBC JdBC JdBC
You You must must add add an an import import statement statement to to the the necessary necessary types: types: You must add an import statement to the necessary types: import java.sql.*; import java.sql.*;
Then Then you you must must define define aaa connection connection to to the the database: database: Then you must define connection to the database: conn = DriverManager.getConnection( conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234"); "jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234");
Writing this this connection connection isis is in in fact fact the the only only difficulty difficulty of of writing writing database database applications, applications, as as itit it Writing Writing this connection in fact the only difficulty of writing database applications, as should be be written written correctly correctly and and as as itit it depends depends on on the the specific specific database database product. product. The The method method should should be written correctly and as depends on the specific database product. The method getConnection() has three three parameters. The The first isis aa connection connection string, while while the last last two are are getConnection() getConnection() has has three parameters. parameters. The first first is a connection string, string, while the the last two two are respectively the the username username and and the the password password to to the the database. database. In In this this case, case, they they are are direct direct respectively respectively the username and the password to the database. In this case, they are direct encoded as as strings, strings, and and itit it may may of of course course not not be be the the solution solution to to an an application application which which isis is used used encoded encoded as strings, and may of course not be the solution to an application which used in an an operation operation condition, condition, but but about about this this later. later. Connection Connection string string consists consists of of the the database database in in an operation condition, but about this later. Connection string consists of the database server that here here is a MySQL server server on the the local machine: machine: server server that that here isis aa MySQL MySQL server on on the local local machine: jdbc:mysql://localhost jdbc:mysql://localhost
This is is followed followed by by the the port port number number (which (which incidentally incidentally is is not not necessary, necessary, since since 3306 3306 is This This is followed by the port number (which incidentally is not necessary, since 3306 isis the default default port port number number for for MySQL), MySQL), and and finally finally follows follows the the name name of of the the database, database, which which the the default port number for MySQL), and finally follows the name of the database, which here is is padata. padata. In In this this case, case, there there is is also also provided provided an an information information that that the the database database does does here here is padata. In this case, there is also provided an information that the database does not require an SSL connection. If you need to use a database on another machine, you not require require an an SSL SSL connection. connection. If If you you need need to to use use aa database database on on another another machine, machine, you you not must type something else than localhost (possible an IP) and you may also need to use must type type something something else else than than localhost localhost (possible (possible an an IP) IP) and and you you may may also also need need to to use use must a different different port port number. number. Finally, Finally, be be aware aware that that the the connection connection string string looks looks different different if is aa different port number. Finally, be aware that the connection string looks different ifif isis another database database than than MySQL. MySQL. another another database than MySQL. After the the connection connection is is defined defined the the program program creates creates of of aa Statement, Statement, which which is is an an object object that that After After the connection is defined the program creates of a Statement, which is an object that represents aa SQL SQL statement, statement, and and the the statement statement is executed executed by by the the method method executeQuery(), executeQuery(), represents represents a SQL statement, and the statement isis executed by the method executeQuery(), wherein the the parameter parameter is is a SQL SQL SELECT SELECT command. command. The The result result of of this this method method is a ResultSet, ResultSet, wherein wherein the parameter is aa SQL SELECT command. The result of this method isis aa ResultSet, which is a collection with an object for each of the rows, the SQL command has extracted which isis aa collection collection with with an an object object for for each each of of the the rows, rows, the the SQL SQL command command has has extracted extracted which from the database. After the statement is successful excuted, the application performs from the the database. database. After After the the statement statement isis successful successful excuted, excuted, the the application application performs performs aaa from loop that that iterates iterates over over the the rows, rows, and and for for each each row row prints prints aa line line with with the the values values of of the the row’s row’s loop loop that iterates over the rows, and for each row prints a line with the values of the row’s fields and and thus thus the the values values in in each each column. column. You You should should note, note, how how to to refer refer to to values values using using fields fields and thus the values in each column. You should note, how to refer to values using methods in the class ResultSet and the column names from the database. methods in in the the class class ResultSet ResultSet and and the the column column names names from from the the database. database. methods The most most database database operations operations can can raise raise a SQLException, SQLException, so so the the statements statements are are placed placed in in aa The The most database operations can raise aa SQLException, so the statements are placed in a try block. The associated finally block closes the Statement and the Connection, and it is try block. block. The The associated associated finally finally block block closes closes the the Statement Statement and and the the Connection, Connection, and and itit isis try important to release the resources allocated. important to to release release the the resources resources allocated. allocated. important
Download free eBooks at bookboon.com 13 13 13
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS
JDBC JdBC
IfIf you you executes executes the the program, program, you you get get the the following following result, result, where where II have have only only shown shown the the first firstlines: lines: Gorm den Gamle Harald Blåtand Svend Tveskæg Harad d. 2. Knud den Store
KING KING KING KING KING
0 958 958 987 987 1014 1014 1018 1018 1035
DK DK DK DK DK
As As isis apparent apparent from from this this example, example, itit isis basically basically simple simple toto perform perform aa data data operation operation from from aaJava Javaprogram. program.Of Ofcourse coursethere thereisismore moretototell tellthan thanthis thisexample exampleshows, shows,and andthe thethe thenext next chapter chaptershows showsmany manyother otherexamples, examples,but butthe thedifferences differencesare areconcerning concerningSQL SQLactually actuallymuch much more morethan thanJava. Java.
EXERCISE EXERCISE11 You You must must write write aa program program that that looks looks like like HelloJDBC, HelloJDBC, but but the the program program should should only only print print the the name name and and the the years years and and only only for for those those persons persons who who are are either either kings kings or or queens, queens, and and whose whosereign reignstarts startsbefore before1500. 1500.
Download free eBooks at bookboon.com 1414
JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA
dataBase operations operatIons Database
3 DATABASE OPERATIONS 3 The following describes a program, called DbOperations consisting of several test methods. The The methods should show how to perform the most basic database operations using JDBC, where I only care about operations that maintains the database tables and hence SQL INSERT, UPDATE and DELETE statements, as well as operations that extract data from tables and thus SQL SELECT.
3.1 SQL STATEMENTS 3.1 The following test method uses the table history, and starts to delete a row in the table, The insert a row, execute a query, update a row and finally execute a query again. This means that the method performs all the above four database operations. The code is as follows: private static void test01() { try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234")) { Statement stmt = conn.createStatement(); System.out.println(stmt.executeUpdate(
The Wake the only emission we want to leave behind
.QYURGGF'PIKPGU/GFKWOURGGF'PIKPGU6WTDQEJCTIGTU2TQRGNNGTU2TQRWNUKQP2CEMCIGU2TKOG5GTX 6JGFGUKIPQHGEQHTKGPFN[OCTKPGRQYGTCPFRTQRWNUKQPUQNWVKQPUKUETWEKCNHQT/#0&KGUGN6WTDQ 2QYGTEQORGVGPEKGUCTGQHHGTGFYKVJVJGYQTNFoUNCTIGUVGPIKPGRTQITCOOGsJCXKPIQWVRWVUURCPPKPI HTQOVQM9RGTGPIKPG)GVWRHTQPV (KPFQWVOQTGCVYYYOCPFKGUGNVWTDQEQO
Download free eBooks at bookboon.com 15 15
Click on the ad to read more
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA
Database operations dataBase operatIons operatIons dataBase
"DELETE FROM FROM history history WHERE WHERE name name LIKE LIKE 'Ragnar 'Ragnar Lodbrog'")); Lodbrog'")); "DELETE System.out.println(stmt.executeUpdate( System.out.println(stmt.executeUpdate( "INSERT INTO INTO history history (name) (name) VALUES('Ragnar VALUES('Ragnar Lodbrog')")); Lodbrog')")); "INSERT ResultSet res res == stmt.executeQuery("SELECT stmt.executeQuery("SELECT name, name, title, title, birth, birth, death, death, country country ResultSet FROM history history WHERE WHERE name name LIKE LIKE 'Ragnar 'Ragnar Lodbrog'"); Lodbrog'"); FROM while(res.next()) while(res.next()) System.out.printf("%-25s%-10s%5d%5d %s\n", %s\n", res.getString("name"), res.getString("name"), System.out.printf("%-25s%-10s%5d%5d res.getString("title"), res.getInt("birth"), res.getInt("birth"), res.getInt("death"), res.getInt("death"), res.getString("title"), res.getString("country")); res.getString("country")); System.out.println(stmt.executeUpdate("UPDATE history history SET SET title title == 'Viking', 'Viking', System.out.println(stmt.executeUpdate("UPDATE country == 'DK' 'DK' WHERE WHERE name name LIKE LIKE 'Ragnar 'Ragnar Lodbrog'")); Lodbrog'")); country res == stmt.executeQuery("SELECT stmt.executeQuery("SELECT name, name, title, title, birth, birth, death, death, country country FROM FROM history history res WHERE name name LIKE LIKE 'Ragnar 'Ragnar Lodbrog'"); Lodbrog'"); WHERE while(res.next()) System.out.printf("%-25s%-10s%5d%5d System.out.printf("%-25s%-10s%5d%5d %s\n", %s\n", while(res.next()) res.getString("name"), res.getString("title"), res.getString("title"), res.getInt("birth"), res.getInt("birth"), res.getString("name"), res.getInt("death"), res.getString("country")); res.getString("country")); res.getInt("death"), }} catch (SQLException (SQLException ex) ex) catch {{ System.out.println(ex); System.out.println(ex); }} }}
IfIf the the method method isis performed, performed, you you get get the the result: result: 00 11 Ragnar Lodbrog Lodbrog Ragnar 1 1 Ragnar Lodbrog Lodbrog Ragnar
NULL NULL VIKING VIKING
00 00
null 00 null DK 00 DK
In the the same same manner manner as as in in the the program program HelloJDBC HelloJDBC the the first first thing thing is to open open aaa connection connection In the same manner as in the program HelloJDBC the first thing isis to to open connection In to the the database, database, and and it done in in exactly exactly the the same same way, way, but but with with the the difference, difference, that that the the to the database, and itit is isis done done in exactly the same way, but with the difference, that the to Connection object object this this time time is created within within the the parenteses parenteses in in the the try try statement. statement. This This means means Connection object this time isis created created within the parenteses in the try statement. This means Connection that the the connection connection is automatically closed closed when when the the method method exits exits the the try try block, block, and and in in that the connection isis automatically automatically closed when the method exits the try block, and in that the same same manner manner as as in in closing closing files files it provides aaa more more simple simple and and also also more more readable readable code. code. the same manner as in closing files itit provides provides more simple and also more readable code. the should be be noted noted that that when when aaa database database connection connection is closed, it also closes closes any any opening opening ItIt should should be noted that when database connection isis closed, closed, itit also also closes any opening It statements that that may may be be associated associated with with the the object. object. statements that may be associated with the object. statements
Download free eBooks at bookboon.com 16 16 16
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Database operations dataBase operatIons
The and the the next next statement statement performs performs aa SQL SQL The try try block block starts starts to to create create aa Statement Statement object, object, and DELETE. which, in in addition addition to to DELETE DELETE DELETE. It It isis executed executed with with the the method method executeUpdate() executeUpdate() which, isis used The method method returns returns the the number number used to to perform perform INSERT INSERT and and UPDATE UPDATE statements. statements. The of delete the the rows rows in in which which the the name’s name’s of rows rows that that have have changed. changed. In In this this case, case, the the statement statement delete value the method method is is run, run, there there may may not not be be value isis Ragnar Ragnar Lodbrog. Lodbrog. If If this this is is the the first first time time that that the such method has has been been completed, completed, there there are are aa such aa row, row, and and the the method method will will return return 0. 0. If If the the method row method will will return return 11 and and then then will will print print row with with that that value value in in the the column column name, name, and and the the method 11 on on the the screen screen corresponding corresponding to to the the above above result. result. The thus aa row row in in the the table. table. You You should should The next next statement statement performs performs aa SQL SQL INSERT INSERT and and inserts inserts thus note name, which which is is okay okay because because the the note that that the the statement statement only only add add aa value value in in the the column column name, other is executed, executed, the the method method also also prints prints other columns columns allow allow null null values. values. When When this this statement statement is 11 on in the the table. table. on the the screen, screen, because because there there are are inserted inserted one one row row in The and this this time time it’s it’s with with executeQuery(), executeQuery(), The next next statement statement again again performs performs aa SQL SQL SELECT, SELECT, and which extract the the rows rows where where the the column column which just just isis used used to to execute execute aa SELECT. SELECT. The The query query extract name one such such row, row, and and the the row row isis printed printed in in name has has the the value value Ragnar Ragnar Lodbrog. Lodbrog. There There is is only only one the third line line above. above. Note Note that that the the method method the next next statement. statement. The The result result is is as as shown shown in in the the third loops while loop. loop. It It is is obviously obviously no no need need loops over over the the objects objects in in the the ResultSet ResultSet object object using using aa while for but it it is is necessary necessary to to perform perform res.next() res.next() for aa loop loop when when II know know that that there there is is only only one one row, row, but to to step step to to the the first first row. row. Finally executeUpdate(), and and as as Finally isis performed performed aa SQL SQL UPDATE and again with the method executeUpdate(), the updated. the last last isis performed performed aa new new query, showing that the row has been updated. PREPAREDSTATEMENTS PREPAREDSTATEMENTS
In Statement object, object, which which In the the above above examples, examples, all all database operations are executed with a Statement isis an statement that that can can not not an object object that that represents represents a static SQL statement, and thus an SQL statement be represents aa parameterized parameterized be changed. changed. There There isis also also a class called PreparedStatement, which represents SQL SQL expression expression SQL statement. statement. The The objective objective of the following test method is to show how, aa SQL can can use use parameters. parameters. The in the the table table history. history. The project project DbOperations DbOperations have a class called Person that represents a row in This means means that that class class contains contains a variable for each column in the table: This public class Person implements { private int id; private String name; private String title;
Comparable, Serializable // number, that is a surrogate key in the database // the person's name // the person's title
Download free eBooks at bookboon.com 17 17
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS
Database operations dataBase dataBaseoperatIons operatIons
private privateInteger Integerbirth; birth; ////birth, birth,start starttotoreign reignororother other private privateInteger Integerdeath; death; ////year yearofofdeath death private privateString Stringcountry; country; // //country countrycode codeas astwo twocharacters characters private privateString Stringdescription; description; ////a adescription descriptionofofthe theperson person
I IIwill willnot notshow showthe thefull fullclass classhere, here,partly partlybecause becauseI IIearlier earlierhave haveseen seenon onan analmost almostidentical identical will not show the full class here, partly because earlier have seen on an almost identical class, class,and andpartly partlybecause becausethe theclass classconsisting consistingprimarily primarilyofof ofget getand andset setmethods. methods.Note, Note,however, however, class, and partly because the class consisting primarily get and set methods. Note, however, that thatthe thetype typeofof ofbirth birthand anddeath deathisisisInteger Integernot notint. int.The Thereason reasonisisisthat thatthe thetwo twocolumns columnsinin in that the type birth and death Integer not int. The reason that the two columns the thedatabase databasecould couldcontain containnull null(and (andan anint intcan cannot notbe benull null).). the database could contain null (and an int can not be null ). The Theclass classDbOperations DbOperationshas hasthe thefollowing followingmethod methodthat thatcreates createsan anArrayList ArrayListwith withsome somePerson Person The class DbOperations has the following method that creates an ArrayList with some Person objects objects(I(I (Ihave haveonly onlyshown shownthe thefirst firstperson person–––there thereare are12): 12): objects have only shown the first person there are 12): private privatestatic staticList ListcreatePersons() createPersons() {{ List Listlist list= =new newArrayList(); ArrayList(); list.add(new list.add(newPerson( Person( "Chlochilaicus", "Chlochilaicus","Legends "Legendsking", king",null, null,null, null,"DK", "DK","Ruled "Ruledabout about515")); 515")); ... ... return returnlist; list; }}
30 FR da EE ys tria
SMS from your computer ...Sync'd with your Android phone & number
l!
Go to
BrowserTexting.com
and start texting from your computer!
...
Download free eBooks at bookboon.com 18 18 18
BrowserTexting
Click on the ad to read more
JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA
dataBase operations operatIons Database
Then the the test test method: method: Then private static void test02() { List list = createPersons(); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234")) { PreparedStatement stmt = conn.prepareStatement("DELETE FROM history WHERE name LIKE ?"); for (Person pers : list) { stmt.setString(1, pers.getName()); stmt.executeUpdate(); } stmt = conn.prepareStatement("INSERT INTO history (name, title, birth, death, country, description) VALUES (?, ?, ?, ?, ?, ?)"); for (Person pers : list) { stmt.setString(1, pers.getName()); stmt.setString(2, pers.getTitle()); if (pers.getBirth() == null) stmt.setNull(3, java.sql.Types.INTEGER); else stmt.setInt(3, pers.getBirth()); if (pers.getDeath() == null) stmt.setNull(4, java.sql.Types.INTEGER); else stmt.setInt(4, pers.getDeath()); stmt.setString(5, pers.getCountry()); stmt.setString(6, pers.getDescription()); stmt.executeUpdate(); } } catch (SQLException ex) { System.out.println(ex); } print("SELECT * FROM history WHERE title LIKE 'Legends king'"); }
First the the method method creates creates aa list list with with the the 12 12 Person Person objects. objects. Then, Then, opening opening aa connection connection First to the the database, database, and and for for this this connection connection isis created created aa PreparedStatement PreparedStatement object. object. The The class class to PreparedStatement isis derived derived from from Statement Statement and and represents represents as as such such aa SQL SQL expression, expression, but but PreparedStatement an expression expression that that may may have have parameters. parameters. In In this this case case itit isis aa SQL SQL DELETE, DELETE, and and there there isis aa an single parameter parameter that that isis indicated indicated with with aa question question mark. mark. The The next next loop loop must must delete delete all all the the single people in in the the list list (if (if available), available), and and for for each each iteration iteration the the loop loop performs performs aa DELETE, DELETE, but but people first itit must must insert insert aa value value for for the the column column name name in in the the SQL SQL expression. expression. That That is, is, that that the the first question mark mark must must be be replaced replaced by by aa value: value: question stmt.setString(1, pers.getNavn());
Download free eBooks at bookboon.com 19 19
JAVA JAVA6: 6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS
Database dataBaseoperations operatIons
Here, Here,11indicates indicatesititisisthe thefirst firstparameter parameter(and (andthere thereisisjust justthe thesame), same),while whilethe thelast lastparameter parameter isis the the value. value. The The value value isis assigned assigned the the stmt stmt object object with with setString() setString() asas the the type type of of the the column column isis VARCHAR. VARCHAR. There There are are similar similar methods methods for for other other column column types. types. When When the the loop loop isis completed, completed, another another PreparedStatement PreparedStatement isis created, created, but but this this time time for for aa SQL SQL INSERT. INSERT. ItIt has has no no fewer fewer than than six six parameters, parameters, and and itit isis used used to to insert insert aa row row in in the the table table for for each each person person in in the the list. list. ItIt happens happens in in aa loop, loop, and and for for each each repetition, repetition, the the 66 parameters parameters are are initialized. initialized. You You should should especially especially note note how how to to specify specify that that aa value value must must be be null. null. Finally Finally the the test test method method perfoms perfoms the the method method print() print() with with aa SQL SQL SELECT SELECT asas parameter, parameter, which which isis aa method method that that prints prints the the rows rows extracted. extracted.
EXERCISE EXERCISE 22 You You should should use use MySQL MySQLWorkbench Workbench to to add add aa new new table table to to the the database database padata. padata. You You should should do do this this by by writing writing aa script script (the (the same same way way asas shown shown for for the the table table history) history) when when the the table table should should be be named named currency, currency, and and itit should should have have three three columns: columns: code, which which must must be be aa currency currency code code of of three three characters, characters, which which must must be be the the 1. 1. code, primary primary key key 2. 2. name, name, that that must must be be the the name name of of the the currency currency and and can can be be up up to to 30 30 characters characters 3. 3. rate, rate, which which must must be be the the exchange exchange rate rate and and having having the the type type DECIMAL DECIMAL with with room room for for 10 10 digits digits and and 44 after after the the decimal decimal point point You You must must then then write write aa program program using using the the following following array array to to update update the the currency currency table. table. The The program program should should start start by by deleting deleting the the entire entire contents contents of of the the table table (with (with aa simple simple DELETE), DELETE), and and then then itit must must use use aa PreparedStatment PreparedStatment and and insert insert aa row row for for each each string string in in the the array: array: private static String[] kurser = { "Danske kroner;DKK;100.00", "Euro;EUR;746.00", "Amerikanske dollar;USD;674.44", "Britiske pund;GBP;1034.10", "Svenske kroner;SEK;79.31", "Norske kroner;NOK;79.68", "Schweiziske franc;CHF;685.66", "Japanske yen;JPY;5.6065", "Australske dollar;AUD;487.61", "Brasilianske real;BRL;171.98", "Bulgarske lev;BGN;381.43", "Canadiske dollar;CAD;510.19", "Filippinske peso;PHP;14.40", "Hongkong dollar;HKD;87.02", "Indiske rupee;INR;10.38",
Download free eBooks at bookboon.com 20 20
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Database operations dataBase operatIons
"Indonesiske rupiah;IDR;0.0494", "Israelske shekel;ILS;174.48", "Kinesiske Yuan renminbi;CNY;106.17", "Kroatiske kuna;HRK;97.87", "Malaysiske ringgit;MYR;157.78", "Mexicanske peso;MXN;40.65", "New Zealandske dollar;NZD;458.77", "Polske zloty;PLN;173.82", "Rumænske lei;RON;168.13", "Russiske rubel;RUB;10.42", "Singapore dollar;SGD;483.72", "Sydafrikanske rand;ZAR;49.08", "Sydkoreanske won;KRW;0.5933", "Thailandske baht;THB;19.00", "Tjekkiske koruna;CZK;27.53", "Tyrkiske lira;TRY;231.78", "Ungarske forint;HUF;2.385" };
To insert a value for for the the rate rate in in aa PreparedStatement, PreparedStatement, you youmust mustspecify specifythat thatthe thetype typeis is DECIMAL, and here here you you can can use use setBigDecimal(). setBigDecimal(). Before you run the the program, program, you you may may update updatethe thearray arraywith withtoday’s today’scurrent currentrates. rates.
Brain power
By 2020, wind could provide one-tenth of our planet’s electricity needs. Already today, SKF’s innovative knowhow is crucial to running a large proportion of the world’s wind turbines. Up to 25 % of the generating costs relate to maintenance. These can be reduced dramatically thanks to our systems for on-line condition monitoring and automatic lubrication. We help make it more economical to create cleaner, cheaper energy out of thin air. By sharing our experience, expertise, and creativity, industries can boost performance beyond expectations. Therefore we need the best employees who can meet this challenge!
The Power of Knowledge Engineering
Plug into The Power of Knowledge Engineering. Visit us at www.skf.com/knowledge
Download free eBooks at bookboon.com 21 21
Click on the ad to read more
JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
ResultSet resultset
4 RESULTSET 4 RESULTSET The The most most complex complex SQL SQL statement statement isis SELECT, SELECT, and and itit isis aa very very complex complex statement statement with with many many options. options. From From aa Java Java program program you you can can perform perform aa SQL SQL SELECT SELECT with with executeQuery(), executeQuery(), and and although although the the SELECT SELECT statement statement can can be be complex, complex, the the result result seen seen from from the the Java Java program program isis always always the the same: same: AA ResultSet ResultSet object. object. You You can can think think of of the the object object as as aa collection collection of of objects objects with with an an internal internal cursor cursor that that points points to to aa current current object object (a (a row), row), or or the the cursor cursor isis null null ifif itit isis not not pointing pointing to to anything. anything. The The class class ResultSet ResultSet defines defines many many methods methods that that can can basically basically be be divided divided into into three three kinds: kinds: 1. 1. methods methods to to move move the the cursor cursor 2. 2. get get methods methods that that returns returns the the value value for for aa column column at at the the current current row row 3. 3. update update methods methods that that update update the the column column value value for for the the current current row row and and you you even even have have the the opportunity opportunity to to write write the the changes changes back back to to the the database database To To create create aa Statement Statement object, object, II have have so so far far used used the the following following syntax: syntax: Statement stmt = connection.createStatement();
that that creates creates aa Statement Statement object, object, but but createStatement() createStatement() has has an an override override of of the the form: form: createStatement(int resultSetType, int resultSetConcurrency)
Here you you can can for for the the first first parameter parameter set set three three values: values: Here 1. ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_FORWARD_ONLY, that that means, means, that that the the cursor cursor can can move move forward forward 1. and isis the the default default value value and 2. ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_INSENSITIVE, that that means, means, that that the the cursor cursor kan kan move move 2. both back back and and forth, forth, and and that that the the ResultSet ResultSet isis not not updated updated with with changes changes that that other other both users had had to to make make to to the the database database after after this this ResulSet ResulSet isis created created users 3. ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.TYPE_SCROLL_SENSITIVE, which which means means the the same same as as above, above, but but with with 3. the difference difference that that the the resultset resultset isis updated updated with with changes changes that that other other users users had had to to the make to to the the database database after after this this ResulSet ResulSet isis created created make As default default aa ResulSet ResulSet isis readonly, readonly, but but for for the the last last of of above above two two parameters parameters there there are are two two options options As 1. ResultSet.CONCUR_READ_ONLY, ResultSet.CONCUR_READ_ONLY,that thatcreates createsaareadonly readonlyResultSet ResultSetand andisisthe thedefault default 1. 2. ResultSet.CONCUR_UPDATABLE, ResultSet.CONCUR_UPDATABLE, which which creates creates aa ResultSet, ResultSet, that that isis updatable updatable 2.
Download free eBooks at bookboon.com 22 22
JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
ResultSet resultset
You can set the same parameters for prepareStatement() with the following syntax: prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
A ResulSet has many ways to navigate the cursor, and you are encouraged to examine the options. They are basically self-explanatory, and the following test method (which is a method in DbOperations) gives examples of the use of the methods on a ResultSet, where you can scroll back and forth: private static void test03() { try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234")) { Statement stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet res = stmt.executeQuery("SELECT name, birth, death FROM history where title LIKE 'King' OR title LIKE 'Queen'"); res.last(); print(res); res.first(); print(res); res.next(); print(res); res.previous(); print(res); res.absolute(50); print(res); res.relative(-5); print(res); res.afterLast(); while (res.previous()) if (res.getString(1).startsWith("Gorm")) break; print(res); System.out.println(res.getRow()); res.last(); System.out.println(res.getRow() + 1); } catch (SQLException ex) { System.out.println(ex); } }
Download free eBooks at bookboon.com 23 23
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA6: 6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS
resultset ResultSet resultset
If you performs the method, you get the result: IfIf you you performs performs the the method, method, you you get get the the result: result: Margrethe d. 2. Margrethe d. 2. Gorm den Gamle Gorm den Gamle Harald Blåtand Harald Blåtand Gorm den Gamle Gorm den Gamle Frederik d. 9. Frederik d. 9. Christian d. 8. Christian d. 8. Gorm den Gamle Gorm den Gamle 1 1 52 52
1972 1972 0 0 958 958 0 0 1947 1947 1839 1839 0 0
0 0 958 958 987 987 958 958 1972 1972 1848 1848 958 958
Each line line are are printed printed with with the the method method Each Each line are printed with the method private static void print(ResultSet res) private static void print(ResultSet res) { { try try { { String name = res.getString(1); String name res.getString(1); int birth = = res.getInt(2); int death birth = = res.getInt(3); res.getInt(2); int int death = res.getInt(3); System.out.printf("%-20s%5d%5d\n", name, birth, death); } System.out.printf("%-20s%5d%5d\n", name, birth, death); }
> Apply now redefine your future
- © Photononstop
AxA globAl grAduAte progrAm 2015
axa_ad_grad_prog_170x115.indd 1
19/12/13 16:36
Download free eBooks at bookboon.com 24
24 24
Click on the ad to read more
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
ResultSet resultset resultset
catch catch (Exception (Exception ex) ex) {{ System.out.println(ex); System.out.println(ex); }} }}
AA resultset resultset has has aa number number of of methods methods used used to to retrieve retrieve the the values values for for the the current current row, row, and and in in the the foregoing foregoing examples, examples, II each each time time has has referenced referenced the the values values with with the the column column name. name. Actually, Actually, itit isis also also allowed allowed to to enter enter an an index, index, starting starting with with 11 for for the the first first column. column. You You should should note note that that the the index index does does not not refer refer to to the the physical physical table, table, but but the the columns columns specified specified in in the the SELECT SELECT statement. statement. In In this this case, case, there there are are three three columns, columns, and and the the indexes indexes are are therefore therefore 1, 1, 22 and and 3. 3.
4.1 4.1 4.1 UPDATE UPDATE A A RESULTSET RESULTSET The The The following following test test method method shows shows that that one one can can update update aa resultset: resultset: private private static static void void test04() test04() {{ try try (Connection (Connection conn conn == DriverManager.getConnection( DriverManager.getConnection( "jdbc:mysql://localhost:3306/padata?useSSL=false", "jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "pa", "Volmer_1234")) "Volmer_1234")) {{ Statement Statement stmt stmt == conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet.CONCUR_UPDATABLE); ResultSet ResultSet res res == stmt.executeQuery("SELECT stmt.executeQuery("SELECT ** FROM FROM history"); history"); insert(res); insert(res); res.last(); res.last(); printRow(res); printRow(res); update(res, update(res, "King", "King", "Probably "Probably lived lived between between the the years years 400 400 and and 500"); 500"); printRow(res); printRow(res); update(res, update(res, "Legends "Legends king", king", res.getString("description") res.getString("description") ++ "" and and his his story story is is described described in in Rolf Rolf Krake's Krake's Saga"); Saga"); printRow(res); printRow(res); while while (true) (true) {{ res res == stmt.executeQuery("SELECT stmt.executeQuery("SELECT id id FROM FROM history history WHERE WHERE name name LIKE LIKE 'Rolf%'"); 'Rolf%'"); if if (res.next()) (res.next()) {{ int int id; id; System.out.println(id System.out.println(id == res.getInt("id")); res.getInt("id")); print("SELECT print("SELECT ** FROM FROM history history WHERE WHERE id id == "" ++ id); id); delete(res); delete(res); }} else else break; break; }} }}
Download free eBooks at bookboon.com 25 25 25
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
} }
ResultSet resultset resultset
catch catch (SQLException (SQLException ex) ex) { { System.out.println(ex); System.out.println(ex); } }
First, you notice that the creation of Statement object that allows you to update ResultSet. First, First,you younotice noticethat thatthe thecreation creationof ofaaaStatement Statementobject objectthat thatallows allowsyou youto toupdate updateaaaResultSet. ResultSet. Next, all rows are extracted from the table history, and then the method insert() called Next, Next, all all rows rows are are extracted extracted from from the the table table history, history, and and then then the the method method insert() insert() isis is called called with the ResultSet as a parameter: with with the the ResultSet ResultSet asas aa parameter: parameter: private private static static void void insert(ResultSet insert(ResultSet res) res) { { try try { { res.moveToInsertRow(); res.moveToInsertRow(); res.updateString("name", "Rolf Krake"); res.updateString("name", "Rolf Krake"); res.updateString("country", "DK"); res.updateString("country", "DK"); res.insertRow(); res.insertRow(); } } catch (SQLException ex) catch (SQLException ex) { { System.out.println(ex); System.out.println(ex); } } } }
This method adds a new row to the ResultSet object and assigns values to two of the columns. This This method method adds adds aa new new row row to to the the ResultSet ResultSet object object and and assigns assigns values values to to two two of of the the columns. columns. The last method writes the changes physically back to the database. IfIfyou do not want that, The last method writes the changes physically back to the database. you do not want The last method writes the changes physically back to the database. If you do not want that, that, you can omit this statement, and the row isisjust inserted in the ResultSet object in memonry. you can omit this statement, and the row just inserted in the ResultSet object in memonry. you can omit this statement, and the row is just inserted in the ResultSet object in memonry. After the new row isisinserted, the test method set the cursor to the last row and the prints After After the the new new row row is inserted, inserted, the the test test method method set set the the cursor cursor to to the the last last row row and and the the prints prints the row by aamethod printRow(). The next statement calls aamethod update(), which updates the row by method printRow(). The next statement calls method update(), which updates the row by a method printRow(). The next statement calls a method update(), which updates the row that the cursor points to: the the row row that that the the cursor cursor points points to: to: private description) private static static void void update(ResultSet update(ResultSet res, res, String String title, title, String String description) { { try try { { res.updateString("title", title); res.updateString("title", title); res.updateString("description", res.updateString("description", description); description); res.updateRow(); res.updateRow(); } } catch (SQLException ex) catch (SQLException ex) { { System.out.println(ex); System.out.println(ex); } } } }
Download free eBooks at bookboon.com 26 26 26
JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE APPLICATIONS
ResultSet resultset
There statement, which which writes writes the the changes changes There is is updated two columns, and again it’s the last statement, back the row row again, again, so so you you can can see see that that the the back to to the database. The test method prints then the changes once again. again. changes are made, after which the row is updated once Next, where itit starts starts to to execute execute aa query query on on Next, the the method performs an infinite while loop where persons where the name starts with Rolf. There should only persons only be be 1. 1. If If there there isis such such aa row row (res. (res. next() is is true) the row is removed with the method delete(). next() delete(). If If the the row row isis not not found found aa break break performed, and the loop stops. The goals is to show isis performed, show that that the the updates updates are are physically physically in in the database, database, so that in the next iteration, no rows are found. the found. The The method method delete() delete() isis quite quite simple and deletes the row that the cursor points to: simple private static void delete(ResultSet res) { try { res.deleteRow(); } catch (SQLException ex) { System.out.println(ex); } }
LIGS University based in Hawaii, USA is currently enrolling in the Interactive Online BBA, MBA, MSc, DBA and PhD programs:
▶▶ enroll by October 31st, 2014 and ▶▶ save up to 11% on the tuition! ▶▶ pay in 10 installments / 2 years ▶▶ Interactive Online education ▶▶ visit www.ligsuniversity.com to find out more!
Note: LIGS University is not accredited by any nationally recognized accrediting agency listed by the US Secretary of Education. More info here.
Download free eBooks at bookboon.com 27 27
Click on the ad to read more
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
ResultSet resultset resultset
You You should note that the test method’s while loop in case there are found row calls the You should should note note that that the the test test method’s method’s while while loop loop in in case case there there are are found found aaa row row calls calls the the method print() with a SQL expression as a parameter. The objective is to show that the method print() print() with with aa SQL SQL expression expression as as aa parameter. parameter. The The objective objective is is to to show show that that the the method new row is available on request associated with another connection, and thus the row new new row row is is available available on on request request associated associated with with another another connection, connection, and and thus thus the the row row isis is physically stored in the database. If you performs the test method, the result could be: physically stored in the database. If you performs the test method, the result could be: physically stored in the database. If you performs the test method, the result could be: Rolf Rolf Krake Krake null null
null null
0 0
0 0 DK DK
Rolf King 0 0 Rolf Krake Krake King 0 0 DK DK Probably lived lived between the years years 400 400 and and 500 500 Probably between the Rolf Legends 0 Rolf Krake Krake Legends king king 0 Probably lived between the years 400 and Probably lived between the years 400 and story story is is described described in in Rolf Rolf Krake's Krake's Saga Saga
0 0 DK DK 500 and his his 500 and
70 70 Rolf Krake Legends king king 0 0 DK DK Rolf Krake Legends 0 0 Probably lived between the years 400 and 500 and his his Probably lived between the years 400 and 500 and story story is is described described in in Rolf Rolf Krake's Krake's Saga Saga
The test method also uses method printRow(), which prints row on the screen (the row The The test test method method also also uses uses aaa method method printRow(), printRow(), which which prints prints aaa row row on on the the screen screen (the (the row row that the cursor points to). The method requires no special explanation and is not shown that the cursor points to). The method requires no special explanation and is not shown that the cursor points to). The method requires no special explanation and is not shown here, but has statement that commented out: here, here, but but itit it isis is has has aaa statement statement that that isis is commented commented out: out: // // System.out.println(res.rowInserted() System.out.println(res.rowInserted() + + " " " " + + res.rowUpdated() res.rowUpdated() + + " " " " + + res.rowDeleted()); res.rowDeleted());
When commented out, simply because does not work. The method should test When itit it isis is commented commented out, out, itit it isis is simply simply because because itit it does does not not work. work. The The method method should should test test When whether a ResultSet has a row that is inserted, updated, or deleted, and where the changes whether aa ResultSet ResultSet has has aa row row that that isis inserted, inserted, updated, updated, or or deleted, deleted, and and where where the the changes changes whether are not not yet yet written written back back to to the the database. database. Note Note specifically specifically that that when when aaa row row isis is deleted, deleted, there there are not yet written back to the database. Note specifically that when row deleted, there are nothing else, than the row marked as deleted in the resultset, but not removed. is nothing nothing else, else, than than the the row row isis is marked marked as as deleted deleted in in the the resultset, resultset, but but itit it isis is not not removed. removed. isis These methods are described in the JDBC standard, but it is not the same as the supplier of These methods methods are are described described in in the the JDBC JDBC standard, standard, but but itit isis not not the the same same as as the the supplier supplier of of These the JDBC driver implements these methods and it does not apply to the JDBC driver for the JDBC JDBC driver driver implements implements these these methods methods and and itit does does not not apply apply to to the the JDBC JDBC driver driver for for the MySQL. The The lesson lesson isis is that that whether whether the the characteristics characteristics of of the the JDBC JDBC standard standard isis is implemented, implemented, MySQL. The lesson that whether the characteristics of the JDBC standard implemented, MySQL. depends on the specific driver, and thus of the database product used, but also the version depends on on the the specific specific driver, driver, and and thus thus of of the the database database product product used, used, but but also also the the version version depends of the driver. of the the driver. driver. of
Download free eBooks at bookboon.com 28 28 28
JAVA6: 6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS JAVA
resultset ResultSet
4.2 MUNICIPALITIES MUNICIPALITIES AND AND ZIPCODES ZIPCODES 4.2 Following the the above, above, II will will show show aa more more realistic realistic example example of of aa database database application. application. The The Following database isis still still padata, padata, but but II will will expands expands itit with with four four new new tables. tables. The The first first should should be be aa database table of of Danish Danish regions: regions: table regnr regnr
name name
1081 1081
RegionNordjylland Nordjylland Region
1082 1082
RegionMidtjylland Midtjylland Region
1083 1083
RegionSyddanmark Syddanmark Region
1084 1084
RegionHovedstaden Hovedstaden Region
1085 1085
RegionSjælland Sjælland Region
and isis thus thus aa simple simple table table with with two two columns columns and and five five rows. rows. The The next next table table isis aa table table of of and Danish municipalities, municipalities, where where each each municipality municipality isis recorded recorded as as Danish 1. the the municipality municipality number number (a(a unique unique number number of of 33 digits) digits) 1. 2. the the municipality municipality name name 2. 3. the the region, region, that that the the municipalty municipalty belongs belongs to to 3. 4. the the municipality’s municipality’s area area in in square square kilometers kilometers 4. 5. the the municipality’s municipality’s inhabitants inhabitants 5. 6. year year of of the the municipality’s municipality’s inhabitants inhabitants 6. The region region isis the the region region number, number, so so there there isis aa 1:n 1:n relation relation between between municipalities municipalities and and The regions, such such that that each each municipality municipality isis linked linked to to aa specific specific region. region. regions, The third third table table isis aa table table of of Danish Danish zip zip codes codes and and isis aa simple simple table table with with two two columns columns that that The contain respectively respectively the the code code and and the the city city name. name. contain municipality uses uses several several zip zip codes, codes, and and aa specific specific zip zip code code can can actually actually be be used used by by several several AA municipality municipalities,and andsuch suchthere thereisisan anm:n m:nrelation relationbetween betweenmunicipalities municipalitiesand andzip zipcodes. codes.Such Suchaa municipalities, relationshipisisimplemented implementedwith withaatable tablewhere whereaarow rowconnects connectsaazip zipcode codeand andaamunicipality. municipality. relationship Accordingly, you you can can expand expand the the database database with with four four new new tables tables using using the the following following script: script: Accordingly, use padata; drop table if drop table if drop table if drop table if
exists exists exists exists
post; municipality; region; zipcode;
Download free eBooks at bookboon.com 29 29
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
ResultSet resultset
create table region ( regnr int not null primary key, name varchar(30) not null ); create table municipality ( munnr int not null primary key, name varchar(30) not null, regnr int not null, area decimal(10, 2), number int, year int, foreign key (regnr) references region(regnr) ); create table zipcode ( code char(4) not null primary key, city varchar(30) not null );
Download free eBooks at bookboon.com 30 30
Click on the ad to read more
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
ResultSet resultset resultset
create table post create table post ( ( code char(4) not null, code char(4) not null, munnr int not null, munnr int not null, primary key (code, munnr), primary key (code, munnr), foreign key (code) references zipcode(code), foreign key (code) references zipcode(code), foreign key (munnr) references municipality(munnr) foreign key (munnr) references municipality(munnr) ); ); insert insert insert insert insert insert insert insert insert insert
into into into into into into into into into into
region region region region region region region region region region
values values values values values values values values values values
(1081, (1081, (1082, (1082, (1083, (1083, (1084, (1084, (1085, (1085,
'Region 'Region 'Region 'Region 'Region 'Region 'Region 'Region 'Region 'Region
Nordjylland'); Nordjylland'); Midtjylland'); Midtjylland'); Syddanmark'); Syddanmark'); Hovedstaden'); Hovedstaden'); Sjælland'); Sjælland');
There is not much to explain, but you should note that the script inserts the five rows in There There isis not not much much to to explain, explain, but but you you should should note note that that the the script script inserts inserts the the five five rows rows in in the table region. The script is called CreateDenmark.sql. the the table table region. region. The The script script isis called called CreateDenmark.sql. CreateDenmark.sql. It you performs the script, it creates the four tables, but the tables other than region are all ItIt you you performs performs the the script, script, itit creates creates the the four four tables, tables, but but the the tables tables other other than than region region are are all all empty and contains no data. The books directory contains a file named zipcodes. It is a text empty empty and and contains contains no no data. data. The The books books directory directory contains contains aa file file named named zipcodes. zipcodes. ItIt isis aa text text file that contains 1106 lines with Danish zip codes, where each line contains a code and file file that that contains contains 1106 1106 lines lines with with Danish Danish zip zip codes, codes, where where each each line line contains contains aa code code and and a city name separated by a semicolon. The file should be used to update the table zipcode, aa city city name name separated separated by by aa semicolon. semicolon. The The file file should should be be used used to to update update the the table table zipcode, zipcode, and you can do that with a SQL command LOAD DATA INFILE. It is a command that and and you you can can do do that that with with aa SQL SQL command command LOAD LOAD DATA DATA INFILE. INFILE. ItIt isis aa command command that that MySQL do not like, because it is not without risk, and you can, in principle, copy anything MySQL MySQL do do not not like, like, because because itit isis not not without without risk, risk, and and you you can, can, in in principle, principle, copy copy anything anything into the database. Therefore, you can not immediately execute the command from MySQL into into the the database. database. Therefore, Therefore, you you can can not not immediately immediately execute execute the the command command from from MySQL MySQL Workbench. To use the command to load the content of the file to a database, you has to Workbench. Workbench. To To use use the the command command to to load load the the content content of of the the file file to to aa database, database, you you has has to to place the file in a special directory that only root has access to: place place the the file file in in aa special special directory directory that that only only root root has has access access to: to: /var/lib/mysql-files /var/lib/mysql-files
I have (as root) in this directory created a subdirectory data. Next, I have copied the II have have (as (as root) root) in in this this directory directory created created aa subdirectory subdirectory data. data. Next, Next, II have have copied copied the the file zipcodes to this directory. Then the table can be updated using the following script file file zipcodes zipcodes to to this this directory. directory. Then Then the the table table can can be be updated updated using using the the following following script script (LoadZipcodes.sql ): (LoadZipcodes.sql ): (LoadZipcodes.sql ): use padata; use padata; load data infile '/var/lib/mysql-files/data/zipcodes' into table zipcode load data infile '/var/lib/mysql-files/data/zipcodes' into table zipcode CHARACTER SET UTF8 CHARACTER SET UTF8 fields terminated by ';' lines terminated by '\n' fields terminated by ';' lines terminated by '\n' (code, city); (code, city);
The result result is that the the table zipcode zipcode now have have 1106 rows. rows. The The result isis that that the table table zipcode now now have 1106 1106 rows.
Download free eBooks at bookboon.com 31 31 31
JAVA JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
ResultSet resultset resultset
Then Then there there isis the the table table municipality, municipality, and and the the book’s book’s directory directory has has aa file file municipalities municipalities that that contains contains lines lines with with data data on on Danish Danish municipalities. municipalities. Below Below isis shown shown the the first first three three lines: lines: 773;Morsø Kommune;1081;364.42;20815;2015;7900;7950;7960;7970;7980;7990 787;Thisted Kommune;1081;1095.63;44078;2015;7700;7730;7741;7742;7752; 7755;7760;7770 810;Brønderslev Kommune;1081;633.38;35781;2015;9320;9330;9340;9352;9370; 9382;9440;9480;9700;9740;9750;9760
AA line line contains contains separated separated by by semicolons semicolons 1. 1. municipality municipality number number 2. 2. municipality municipality name name 3. 3. region region number number 4. 4. area area 5. number 5. number of of inhabitants inhabitants 6. 6. year year for for number number of of inhabitants inhabitants This This isis followed followed by by aa variable variable number number of of zip zip codes, codes, which which are are the the zip zip codes codes that that this this municipality uses. For each line in the file there must be inserted a row in the table municipality uses. For each line in the file there must be inserted a row in the table municipality, municipality, and and for for each each zip zip code code aa row row in in the the table table post. post. The The easiest easiest isis to to write write aa small small program program that that reads reads the the file file and and updates updates the the database: database: package createmunicipalities; import import import
java.sql.*; java.io.*; java.math.*;
public class CreateMunicipalities { public static void main(String[] args) { try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "Volmer_1234"); BufferedReader reader = new BufferedReader( new FileReader(System.getProperty("user.home") + "/data/municipalities"))) { Statement stmt = conn.createStatement(); stmt.execute("DELETE FROM post"); stmt.execute("DELETE FROM municipality"); PreparedStatement stmt1 = conn.prepareStatement( "INSERT INTO municipality VALUES(?, ?, ?, ?, ?, ?)"); PreparedStatement stmt2 = conn.prepareStatement( "INSERT INTO post VALUES(?, ?)");
Download free eBooks at bookboon.com 32 32 32
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
ResultSet resultset
for (String line = reader.readLine(); line != null; line = reader.readLine()) { String[] elem = line.split(";"); int munnr = Integer.parseInt(elem[0]); stmt1.setInt(1, munnr); stmt1.setString(2, elem[1]); stmt1.setInt(3, Integer.parseInt(elem[2])); stmt1.setBigDecimal(4, new BigDecimal(elem[3])); stmt1.setInt(5, Integer.parseInt(elem[4])); stmt1.setInt(6, Integer.parseInt(elem[5])); stmt1.executeUpdate(); System.out.println(elem[1]); for (int i = 6; i < elem.length; ++i) { try { stmt2.setString(1, zipcode(elem[i])); stmt2.setInt(2, munnr); stmt2.executeUpdate(); } catch (Exception ex) { System.out.println(munnr + " " + elem[i]); }
33
Download free eBooks at bookboon.com 33
Click on the ad to read more
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
ResultSet resultset resultset
}} }} }} catch catch (Exception (Exception ex) ex) {{ System.out.println(ex); System.out.println(ex); }} }} private private static static String String zipcode(String zipcode(String str) str) {{ if if (str.length() (str.length() == == 3) 3) str str == "0" "0" ++ str; str; return return str; str; }} }}
In In the the the parentheses parentheses parentheses after after after try try try are are are in in in the the the usual usual usual way way way opened opened opened aaa connection connection connection to to to the the the database database database and and and In the the file file file municipalities municipalities municipalities that that that III have have have copied copied copied to to to the the the folder folder folder data data data under under under my my my home home home directory. directory. directory. The The The the first first thing thing thing that that that happens happens happens is isis that that that the the the content content content of of of the the the two two two database database database tables tables tables are are are deleted deleted deleted and and and then then then first are are created created created two two two PreparedStatement PreparedStatement PreparedStatement objects objects objects with with with INSERT INSERT INSERT statements statements statements for for for the the the two two two tables. tables. tables. The The The are next next for for for loop loop loop reads reads reads the the the file file file line line line by by by line, line, line, and and and each each each line line line is isis split split split into into into tokens tokens tokens that that that are are are used used used to to to next initialize initialize the the the parameters parameters parameters of of of stmt1. stmt1. stmt1. After After After having having having inserted inserted inserted aaa row row row in in in the the the table table table municipalities, municipalities, municipalities, initialize there there is isis inner inner inner for for for loop loop loop that that that runs runs runs over over over all all all zip zip zip codes codes codes and and and insert insert insert rows rows rows in in in the the the table table table post post post for for for this this this there municipality. municipality. municipality. You You should should should note note note that that that ititit actually actually actually takes takes takes aaa long long long time time time to to to execute execute execute the the the program. program. program. The The The program program program You executes executes more more more than than than 2000 2000 2000 SQL SQL SQL INSERT INSERT INSERT commands, commands, commands, and and and ititit is isis aaa tedious tedious tedious procces procces procces to to to make make make executes from from Java, Java, Java, as as as shown shown shown in in in this this this example, example, example, and and and there there there are are are also also also as as as shown shown shown later later later better better better ways ways ways to to to ititit from accomplish accomplish the the the same. same. same. accomplish As As an an an example example example of of of aaa program program program that that that uses uses uses the the the new new new tables, tables, tables, determines determines determines the the the following following following test test test method method method As (still (stillaaamethod method methodin in inthe the theprogram program programDbOperations) DbOperations) DbOperations)the the thenumber number numberof of ofresidents residents residentsin in inRegion Region RegionMidtjylland: Midtjylland: Midtjylland: (still private private static static void void test05() test05() {{ try try (Connection (Connection conn conn == DriverManager.getConnection( DriverManager.getConnection( "jdbc:mysql://localhost:3306/padata?useSSL=false", "jdbc:mysql://localhost:3306/padata?useSSL=false", "pa", "pa", "Volmer_1234")) "Volmer_1234")) {{ Statement Statement stmt stmt == conn.createStatement(); conn.createStatement(); ResultSet ResultSet res res == stmt.executeQuery("SELECT stmt.executeQuery("SELECT number number FROM FROM municipality municipality AS AS M, M, region region AS AS RR WHERE WHERE M.regnr M.regnr == R.regnr R.regnr AND AND R.name R.name LIKE LIKE '%Midtjylland'"); '%Midtjylland'"); int int count count == 0; 0; while while (res.next()) (res.next()) count count += += res.getInt("number"); res.getInt("number");
Download free eBooks at bookboon.com 34 34 34
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND DATABASE APPLICATIONS APPLICATIONS AND DATABASE
} }
ResultSet resultset resultset
System.out.println("Number System.out.println("Number of of inhabitants inhabitants in in Region Region Midtjylland: Midtjylland: " " + + count); count); } } catch catch (SQLException (SQLException ex) ex) { { System.out.println(ex); System.out.println(ex); } }
You should note that the only thing new is a little more complex SQL SELECT statement, but from Java there is nothing new.
EXERCISE 3 Write a program that from the numbers in the table municipality on the screen prints the population density in Jutland and Fyn.
PROBLEM 1 You must expand the database padata with two other tables. The first should be named world and must contains the names of all continents: create create table table world world ( ( code code char(2) char(2) not not null null primary primary key, key, name varchar(15) varchar(15) not name not null null ); );
The The table table must must contain contain the the following following data: data: ---------------
AS Asia AS AS Asia Asia AF Africa AF Africa Africa AF NA NA North NA North America America SA SA SA South South America America AN Antarctica AN Antarctica AN Antarctica EU Europe EU Europe Europe EU OC Oceania OC Oceania Oceania OC
The The second second table should contain information on countries: table should contain information on countries: create create table table country country ( ( code2 code2 char(2) char(2) not not null null primary primary key, key, code3 code3 varchar(3), varchar(3), name name varchar(50) varchar(50) not not null, null,
# # # # # #
country country code code country code code country the country's name the country's name
Download free eBooks at bookboon.com 35 35 35
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
ResultSet resultset resultset
area int, # the country's area area int, # the country's area number int, # number of inhabitants number int, # number of inhabitants continent char(2), # continent continent char(2), # continent currency char(3), # currency code currency char(3), # currency code foreign key (continent) references world(code), foreign key (continent) references world(code), foreign key (currency) references currency(code) foreign key (currency) references currency(code) ); );
Write Writeaascript scriptthat thatcreates createsthese thesetwo twotables tablesand andinserts insertsinformation informationabout aboutthe thecontinents continentsin in Write a script that creates these two tables and inserts information about the continents in the the first first table. table. the first table. The The folder folder to to this this book book contains contains aa file file called called countries. countries. ItIt isis aa plain plain text text file file in in which which each each The folder to this book contains a file called countries. It is a plain text file in which each line line contains contains information information about about aa country. country. Below Below isis the the first first lines: lines: line contains information about a country. Below is the first lines: AF;AFG;Afghanistan AF;AFG;Afghanistan AL;ALB;Albanien AL;ALB;Albanien DZ;DZA;Algir DZ;DZA;Algir AS;ASM;Amerikansk Samoa AS;ASM;Amerikansk Samoa US;USA;Amerikas Forenede Stater (USA);US Dollar;USD;553.14 US;USA;Amerikas Forenede Stater (USA);US Dollar;USD;553.14 AD;AND;Andorra AD;AND;Andorra AO;AGO;Angola AO;AGO;Angola AI;AIA;Anguilla AI;AIA;Anguilla
Download free eBooks at bookboon.com 36 36 36
Click on the ad to read more
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
ResultSet resultset resultset
AQ;ATA;Antarktis AQ;ATA;Antarktis AG;ATG;Antigua og og Barbuda Barbuda AG;ATG;Antigua AR;ARG;Argentina AR;ARG;Argentina AM;ARM;Armenien AM;ARM;Armenien AW;ABW;Aruba AW;ABW;Aruba AZ;AZE;Aserbajdsjan AZ;AZE;Aserbajdsjan AU;AUS;Australien;Australsk dollar;AUD;568.80 dollar;AUD;568.80 AU;AUS;Australien;Australsk BS;BHS;Bahama BS;BHS;Bahama BH;BHR;Bahrain BH;BHR;Bahrain
The Thefields fieldsare areseparated separatedby bysemicolons. semicolons.For Foreach eachcountry countrythere thereisisisatat atleast least333fields: fields:country country The fields are separated by semicolons. For each country there least fields: country code codeon on222characters characters(primary (primarykey), key),country countrycode codeon on333characters characters(which (whichmay maybe beblank) blank) code on characters (primary key), country code on characters (which may be blank) and andthe thecountry’s country’sname. name.In Inaddition, addition,there theremay maybe bethree threeadditional additionalfields, fields,that thatisisisthe thename name and the country’s name. In addition, there may be three additional fields, that the name of ofthe thecurrency currencywhich whichthe thecountry countryuses, uses,the thecurrency currencycode codeand andan anexchange exchangerate. rate. of the currency which the country uses, the currency code and an exchange rate. You Youmust mustnow nowwrite writeaaaprogram programthat thatcan canupdate updatethe thetable tablecountry countryby byreading readingthe theabove abovefile. file. You must now write program that can update the table country by reading the above file. IfIfIfthere thereisisisaaacurrency, currency,the thecurrency currencycode codeisisisinserted insertedin inthe thecolumn columnfor forcurrency, currency,otherwise otherwise there currency, the currency code inserted in the column for currency, otherwise the thevalue valueshould shouldjust justbe benull. null.There Thereisisisaaaparticular particularproblem problemwhen whenthe thefile filefor foraaacountry country the value should just be null. There particular problem when the file for country indicates indicatesaaacurrency, currency,and andthat thatcurrency currencynot notexitst exitstin inthe thetable tablecurrency. currency.For Forthese thesecurrencies, currencies, indicates currency, and that currency not exitst in the table currency. For these currencies, the theprogram programmust mustalso alsoupdate updatethe thetable tablecurrency. currency. the program must also update the table currency.
4.3 4.3 STORED STOREDPROCEDURES PROCEDURES 4.3 STORED PROCEDURES AAAstored storedprocedure procedureisisisaaascript scriptthat thatcontains containsSQL SQLstatements statementsthat thatisisisexecuted executedwhen whenthe the stored procedure script that contains SQL statements that executed when the procedure procedureisisisperformed. performed.When Whenone onespeaks speaksof ofaaastored storedprocedure, procedure,itititmeans meansthat thatthe theprocedure procedure procedure performed. When one speaks of stored procedure, means that the procedure isisistranslated translatedand andstored storedin inthe thedatabase, database,which whichmeans meansthat thatitititisisishighly highlyeffective effectiveto toexecute executeaaa translated and stored in the database, which means that highly effective to execute stored storedprocedure. procedure.In InMySQL MySQLWorkbench Workbenchyou youcan cancreate createaaastored storedprocedure procedureby byright-clicking right-clicking stored procedure. In MySQL Workbench you can create stored procedure by right-clicking Stored StoredProcedures Proceduresfor forthe thedatabase databaseunder underSchemas, Schemas,and andyou youget getasas asaaaskeleton skeletonfor foraaaprocedure: procedure: Stored Procedures for the database under Schemas, and you get skeleton for procedure: CREATE PROCEDURE PROCEDURE 'new_procedure' 'new_procedure' () () CREATE BEGIN BEGIN END END
Asan anexample, example,IIIhave havewritten writtenaaavery verysimple simpleprocedure procedurewhich whichOUT OUTparameter parameterreturns returnsthe the As As an example, have written very simple procedure which OUT parameter returns the numberof ofpersons personsin inthe thetable tablehistory historywhere wherethe theyear yearfalls fallswithin withinaaarange: range: number number of persons in the table history where the year falls within range: CREATE PROCEDURE PROCEDURE 'persons' 'persons' (IN (IN aa int, int, IN IN bb CREATE BEGIN BEGIN SELECT count(id) count(id) FROM FROM history history WHERE WHERE (a (a Apply now redefine your future
- © Photononstop
AxA globAl grAduAte progrAm 2015
axa_ad_grad_prog_170x115.indd 1
19/12/13 16:36
Download free eBooks at bookboon.com 151 151
Click on the ad to read more
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Final examples FInal examples
create table publisher ( pubnr int not null, name varchar(40) not null, primary key (pubnr)); create table author ( autnr int not null, firstname varchar(50), lastname varchar(20) not null, primary key (autnr)); create table book ( isbn char(13) not null, title varchar(100) not null, edition int, year char(4), pages int, pubnr int not null, catnr int, primary key (isbn), foreign key (pubnr) references publisher (pubnr), foreign key (catnr) references category (catnr)); create table written ( isbn char(13) not null, autnr int not null, primary key (isbn, autnr), foreign key (isbn) references book (isbn), foreign key (autnr) references author (autnr));
scriptisissimply simplya atext textfile filecontaining containingSQL SQLcommands. commands.IfIfthe thefile fileisisopened openedininMySQL MySQL AAscript Workbench,and andperformed performedthe thescript scriptcreates createsthe thedatabase. database.Preliminary Preliminaryignore ignorethe theindividual individual Workbench, commandsbecause becausethey theyare areallalldealt dealtwith withbelow. below. commands Afterthe thescript scriptisisdone, done,you youhave haveananempty emptydatabase, database,but butyou youmust musthave havesomething somethingtotodo do After with,and andyou youmust mustadd adddata datatotothe thedatabase. database.InInthe thefolder folderfor forthis thisbook bookthere thereare are55text text with, fileswith withdata datafor forthe the55tables: tables: files Category.txt Category.txt Publisher.txt Publisher.txt Author.txt Author.txt Book.txt Book.txt Written.txt Written.txt
Download free eBooks at bookboon.com 152 152
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASE APPLICATIONS APPLICATIONS
Finalexamples examples FInal
IfIfyou (requires you you are are root) root) so so the the database database youcopy copy these these files files to to the the /var/lib/mysql-files/data /var/lib/mysql-files/data (requires can (LoadBooks.sql ): canbe beloaded loaded with with data data using using the the following following script script (LoadBooks.sql ): use books; load data infile '/var/lib/mysql-files/data/Category.txt' into table category fields terminated by '\t' lines terminated by '\r\n'; load data infile '/var/lib/mysql-files/data/Publisher.txt' into table publisher fields terminated by '\t' lines terminated by '\r\n'; load data infile '/var/lib/mysql-files/data/Author.txt' into table author fields terminated by '\t' lines terminated by '\r\n'; load data infile '/var/lib/mysql-files/data/Book.txt' into table book fields terminated by '\t' lines terminated by '\r\n'; load data infile '/var/lib/mysql-files/data/Written.txt' into table written fields terminated by '\t' lines terminated by '\r\n';
Theresult resultisis that that you you now now have have aa simple simple database database with The with 55 tables. tables. SQLDATA DATATYPES TYPES SQL
Asshown showninin the the above above script script that that creates creates the the database database books, As books, then then each each column column has has aa data data type. There are the following options: type. There are the following options: --------
Int, that can contain an integer between -2147483648 and 2147483647. Int, that can contain an integer between -2147483648 and 2147483647. Smallint, that can contain an integer between -32768 and 32767. Smallint, that can contain an integer between -32768 and 32767. Tinyint, that can contain an integer between 0 and 255. Tinyint, that can contain an integer between 0 and 255. Bit, there is 0 or 1 (in MySQL you can also write Bool, that means the same). Bit, there is 0 or 1 (in MySQL you can also write Bool, that means the same). Bigint, that can contain an integer between the two integers -9223372036854775808 Bigint, that can contain an integer between the two integers -9223372036854775808 and 9223372036854775807. and 9223372036854775807. Numeric (or Decimal ) to decimal numbers between -10^38 +1 and 10^38 -1 Numeric (or Decimal ) to decimal numbers between -10^38 +1 and 10^38 -1 Money to currency values and can contain a value between -922337203685477.5808 Money to currency values and can contain a value between -922337203685477.5808 and 922337203685477.5807 and 922337203685477.5807
Download free eBooks at bookboon.com 153 153
JAVA 6: JDBC AND DATABASE APPLICATIONS
Final examples
---------
Smallmoney to currencies values from -214748.3648 to 214748.3647 Float to floating points from -3.40E + 38 to 3.40E + 38 (the type is also called Real). Double to floating points from -1.79E+308 to 1.79F+308. Datetime to timekeeping from 1. January 1753 to 31 December 9999. Smalldatetime to timekeeping from 1. January 1900 to 6. June 2079. Date to dates on the form YYYYMMDD Time to time on the form HHMMSS Char to text of a fixed length with max 255 characters, where the field is filled with blanks. -- Varchar to text of variable length, which can be up to 65535 characters. In addition, there are two types Text and Blob, which fills the same (the same capacity), but are used respectively to text and binary data. They come in several varieties: -----
Tinytext and Tinyblob with space for max 255 bytes. Text and Blob with space for max 65535 bytes. Mediumtext and Mediumblob with space for max 16777215 bytes. Longtext and Longblob with space for max 4294967295 bytes.
LIGS University based in Hawaii, USA is currently enrolling in the Interactive Online BBA, MBA, MSc, DBA and PhD programs:
▶▶ enroll by October 31st, 2014 and ▶▶ save up to 11% on the tuition! ▶▶ pay in 10 installments / 2 years ▶▶ Interactive Online education ▶▶ visit www.ligsuniversity.com to find out more!
Note: LIGS University is not accredited by any nationally recognized accrediting agency listed by the US Secretary of Education. More info here.
Download free eBooks at bookboon.com 154
Click on the ad to read more
JAVA 6: JDBC AND DATABASE APPLICATIONS
Final examples
The above applies to MySQL, but other databases can have several data types. In addition to data types, there are similar to other programming languages operators, and in terms to arithmetical operators and operators for comparison the syntax is almost the same as in Java. However, there are some other operators, as I will explain in connection with examples, but the list is as follows: ------------
ALL AND ANY BETWEEN EXISTS IN LIKE NOT OR IS NULL UNIQUE
SQL COMMANDS
SQL is a command language, and there are the following commands: -- CREATE, that is used to create database objects such as tables -- ALTER, that is used to modify existing objects, such as tables -- DROP, that is used to delete objects such as tables These commands are called DDL commands for Data Definition Language. -- GRANT, that is used to assign the rights for users -- REVOKE, that is used to remove rights from users These commands are called DCL commands for Data Control Language. -- INSERT, which is used to insert a row in a table -- UPDATE, which is used to modify the content of one or more rows in a table -- DELETE, which is used to delete one or more rows in a table
Download free eBooks at bookboon.com 155
JAVA JAVA6: 6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Final FInalexamples examples FInal examples
These These commands commands are are called called DML DML commands commands for for Data Data Manipulation Manipulation Language. Language. These commands are called DML commands for Data Manipulation Language. --- SELECT, SELECT, which which isis used used for for extracting extracting rows rows from from one one or or more more tables tables - SELECT, which is used for extracting rows from one or more tables This This command command isis called called aa DQL DQL command command for for Data Data Query Query Language. Language. This command is called a DQL command for Data Query Language. There There are are asas such such 99 commands commands so so SQL SQL should should be be easy easy to to learn, learn, and and itit also also is, is, and and itit isis only only There are as such 9 commands so SQL should be easy to learn, and it also is, and it is only the last, which is complex with a very comprehensive syntax. the last, which is complex with a very comprehensive syntax. the last, which is complex with a very comprehensive syntax. Note Note first first that that SQL SQL does does not not differentiate differentiate between between small small and and capital capital letters, letters, but but in in the the Note first that SQL does not differentiate between small and capital letters, but in the following, following, II generally generally write write SQL SQL names names with with capital capital letters letters and and itit isis only only because because itit for for the the following, I generally write is SQL names with capital letters and it is only because it for the reader reader should should be be clear clear what what is SQL SQL key key words. words. reader should be clear what is SQL key words. As As an an example example isis shown shown aa command command that that creates creates aa database: database: As an example is shown a command that creates a database: CREATE DATABASE books; CREATE DATABASE books;
If you want to delete the database again, you can do it with the command IfIfyou youwant wanttotodelete deletethe thedatabase databaseagain, again,you youcan cando doititwith withthe thecommand command DROP DATABASE books; DROP DATABASE books;
One must of course be wary of a command as above, that you do not delete a database One Onemust mustofofcourse coursebe bewary waryofofaacommand commandasasabove, above,that thatyou youdo donot notdelete deleteaadatabase database with data – unless this is exactly what you want. with data – unless this is exactly what you want. with data – unless this is exactly what you want. If the database management system is used to manage multiple databases (and it will always IfIfthe thedatabase databasemanagement managementsystem systemisisused usedtotomanage managemultiple multipledatabases databases(and (andititwill willalways always be the case), and you opens MySQL Workbench, you must tell which database the SQL be bethe thecase), case),and andyou youopens opensMySQL MySQLWorkbench, Workbench,you youmust musttell tellwhich whichdatabase databasethe theSQL SQL commands should works on. You do this with a command like commands should works on. You do this with a command like commands should works on. You do this with a command like USE books; USE books;
which makes the database books to the current database. which whichmakes makesthe thedatabase databasebooks bookstotothe thecurrent currentdatabase. database. Is the database books the current database, you can create a table as follows: IsIsthe thedatabase databasebooks booksthe thecurrent currentdatabase, database,you youcan cancreate createaatable tableasasfollows: follows: CREATE TABLE publisher ( CREATE TABLEINT publisher pubnr NOT (NULL, pubnr INT NOT NOT NULL, name VARCHAR(40) NULL, name VARCHAR(40) NOT NULL, PRIMARY KEY (pubnr)); PRIMARY KEY (pubnr));
Download free eBooks at bookboon.com 156 156 156
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS
Final FInalexamples examples
Here Here you you creates creates aa table table named named publisher. publisher. The The table table has has two two columns, columns, where where the the first first isis called calledpubnr pubnrand andhas hasthe thetype typeINT INTand andthus thusmust mustcontain containintegers, integers,while whilethe theother otherisiscalled called name and has type VARCHAR to hold max 40 characters and then can contain text. Both name and has type VARCHAR to hold max 40 characters and then can contain text. Both columns columnsare aredefined definedNOT NOTNULL, NULL,and andaarow rowmust musthave haveaavalue valuefor forboth bothpubnr pubnrand andname. name. Finally Finallyisisdefined definedthat thatthe thecolumn columnpubnr pubnrmust mustbe beprimary primarykey. key.The Thecommand commandisiswritten writtenon on several severallines. lines.ItItisisnot notnecessary necessaryand andisisonly onlydone donefor forthe thesake sakeofofreadability, readability,but butyou youshould should note where there is a comma, as they must be there. The command in question may note where there is a comma, as they must be there. The command in question may inin addition additionalso alsobe bewritten writtenasasfollows: follows: CREATE TABLE publisher ( pubnr INT PRIMARY KEY, name VARCHAR(40) NOT NULL );
When I have not specified NOT NULL for the column pubnr, it is because a column When I have not specified NOT NULL for the column pubnr, it is because a column defined as a primary key will automatically be NOT NULL. defined as a primary key will automatically be NOT NULL.
Download free eBooks at bookboon.com 157 157
Click on the ad to read more
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA
Final examples FInal examples FInal examples examples FInal
Below Belowisis isanother anotherexample exampleofof ofaacommand commandthat thatcreates createsaaatable: table: Below another example command that creates table: Below is another example of aa command that creates a table: CREATE TABLE TABLE book book (( CREATE CREATE TABLE book ( isbn CHAR(13) NOT NULL, NULL, isbn CHAR(13) NOT isbn CHAR(13) NOT NULL, title VARCHAR(100) NOT NOT NULL, NULL, title VARCHAR(100) title VARCHAR(100) NOT NULL, edition INT, edition INT, edition INT, year CHAR(4), year CHAR(4), year CHAR(4), pages INT, pages INT, pages INT, pubnr INT, NOT NULL, NULL, pubnr INT, NOT pubnr INT, NOT NULL, catnr INT, catnr INT, catnr INT, PRIMARY KEY KEY (isbn), (isbn), PRIMARY PRIMARY KEY (isbn), FOREIGN KEY (pubnr) REFERENCES REFERENCES publisher publisher (pubnr), (pubnr), FOREIGN KEY KEY (pubnr) (pubnr) FOREIGN REFERENCES publisher (pubnr), FOREIGN KEY KEY (catnr) (catnr) REFERENCES REFERENCES category category (catnr)); (catnr)); FOREIGN FOREIGN KEY (catnr) REFERENCES category (catnr));
Hereyou youcreates createsaaatable tablebook bookwith with777columns, columns,which whichshould shouldcontain containinformation informationabout aboutaaa Here Here you creates table book with columns, which should contain information about Here you creates a table book with 7 columns, which should contain information about a book. Here is the first column is primary key. The next column is defined NOT NULL book. Here is the first column is primary key. The next column is defined NOT NULL book. Here Here is is the the first first column column is is primary primary key. key. The The next next column column is is defined defined NOT NOT NULL NULL book. corresponding to that a book must have a title. The next three columns allow NULL values corresponding to that a book must have a title. The next three columns allow NULL values corresponding to to that that aa book book must must have have aa title. title. The The next next three three columns columns allow allow NULL NULL values values corresponding becauseyou youare arewelcome welcometoto tocreate createaaabook bookwithout withoutknowing knowingwhen whenthe thebook bookisis isreleased, released,the the because because you are welcome create book without knowing when the book released, the because you are welcome to create a book without knowing when the book is released, the editionand andthe thepage pagenumber. number.The Thecolumn columnpubnr pubnrisis isforeign foreignkey keytoto tothe thepublisher publishertable tableand and edition edition and the page number. The column pubnr foreign key the publisher table and edition and the page number. The column pubnr is foreign key to the publisher table and isdefined definedNOT NOTNULL. NULL.This Thismeans meansthat thataaabook bookmust musthave haveaaapublisher. publisher.The Thecolumn columncatnr catnr isis defined NOT NULL. This means that book must have publisher. The column catnr is defined NOT NULL. This means that a book must have a publisher. The column catnr isalso alsoaaaforeign foreignkey key(to (tothe thetable tablecategory), category),but butitit itmay maywell wellbe benull. null.This Thismeans meansthat thataaabook book isis also foreign key (to the table category), but may well be null. This means that book is also a foreign key (to the table category), but it may well be null. This means that a book neednot notbe beassigned assignedtoto toaacategory, category,but butifififthere thereisis isaavalue valueinin inthe thecolumn, column,itit itmust mustbe bethe the need need not be assigned category, but there value the column, must be the need not be assigned to aa category, but if there is aa value in the column, it must be the numberofof ofan anexisting existingcategory. category. number number an existing category. number of an existing category. Ifyou youwant wanttoto todelete deleteaaatable, table,the thesyntax syntaxisis is IfIf you want delete table, the syntax If you want to delete a table, the syntax is DROP TABLE TABLE book; book; DROP DROP TABLE book;
whichdeletes deletesthe thetable tablebook bookwith withall allits itsdata. data.You Youshould shouldnote notethat thatifififyou youinstead insteadtries triestoto to which deletes the table book with all its data. You should note that you instead tries which which deletes the table book with all its data. You should note that if you instead tries to executethe thecommand command execute the command execute execute the command DROP TABLE TABLE publisher; publisher; DROP DROP TABLE publisher;
wouldget getan anerror errorwhen whenthe thetable tablebook bookvia viathe theforeign foreignkey keyrefers referstoto to the the table table publisher. publisher. would get an error when the table book via the foreign key refers would would get an error when the table book via the foreign key refers to the the table table publisher. publisher. Itisis is also also possible possible to to modify modify database database objects. objects. As As an an example example the the following following command command adds adds It ItIt is also also possible possible to to modify modify database database objects. objects. As As an an example example the the following following command command adds adds newcolumn columntoto to the the table table book: book: new column aaaanew new column to the the table table book: book: ALTER TABLE TABLE book book ADD ADD info info VARCHAR(1024); VARCHAR(1024); ALTER ALTER TABLE book ADD info VARCHAR(1024);
Download free eBooks at bookboon.com 158 158 158 158
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Final examples FInal FInal examples examples FInal examples
Similarly, Similarly,the thefollowing followingcommand commandisisused usedtotochange changethe thedata datatype typeofofthe thenew newcolumn: column: Similarly, the following command is used to change the data type of the new column: ALTER ALTER TABLE TABLE book book MODIFY MODIFY info info Text; Text; ALTER TABLE book MODIFY info Text;
IfIfyou youwant wanttotodelete deletethe thenew newcolumn columnagain, again,you youcan cando doititwith withthe thefollowing followingcommand: command: If you want to delete the new column again, you can do it with the following command: ALTER TABLE book DROP COLUMN info; info; ALTER TABLE book DROP COLUMN ALTER TABLE book DROP COLUMN info;
If,If,for forexample exampleititisissuch suchthat thatthe thebook’s book’sedition editionmust mustbe beless lessthan than20, 20,you youcan canexecute execute If, for example it is such that the book’s edition must be less than 20, you can execute the thecommand: command: the command: ALTER ALTER TABLE TABLE book book ADD ADD CONSTRAINT CONSTRAINT editionCheck editionCheck CHECK CHECK (edition (edition < < 20); 20); ALTER TABLE book ADD CONSTRAINT editionCheck CHECK (edition < 20);
where wherethe theconstraint constrainthas hasbeen beengiven givenaaname, name,sosoyou youcan canrefer refertotoititininSQL SQLcommands. commands. where the constraint has been given a name, so you can refer to it in SQL commands. Subsequently, Subsequently,one onecould couldmodficere modficerethis thisconstraint constraintasasfollows: follows: Subsequently, one could modficere this constraint as follows: ALTER ALTER ALTER CHECK CHECK CHECK
TABLE book book ADD ADD CONSTRAINT CONSTRAINT editionCheck editionCheck TABLE TABLE book ADD CONSTRAINT editionCheck (edition IS NULL OR (edition BETWEEN (edition IS NULL OR (edition BETWEEN 1 1 AND AND 19)); 19)); (edition IS NULL OR (edition BETWEEN 1 AND 19));
there would be a more accurate control. there therewould wouldbe beaamore moreaccurate accuratecontrol. control. As a final example the below shows a command that changes the name of a column: As Asaafinal finalexample examplethe thebelow belowshows showsaacommand commandthat thatchanges changesthe thename nameofofaacolumn: column: ALTER TABLE book CHANGE edition edit INT; ALTER TABLE book CHANGE edition edit INT; ALTER TABLE book CHANGE edition edit INT;
I mention the command because it can be useful, but also because it is an example of a mentionthe thecommand commandbecause because itcan can beuseful, useful,but butalso alsobecause becauseititisisan anexample exampleofofaa I Icommand mention whose syntax depends it on the be current database management system. commandwhose whosesyntax syntaxdepends dependson onthe thecurrent currentdatabase databasemanagement managementsystem. system. command There are many other options with the command ALTER but the above gives an impression There are many other options withthe thecommand commandALTER ALTERbut butthe theabove abovegives givesan animpression impression There many other options with of theare syntax and what is possible. thesyntax syntaxand andwhat whatisispossible. possible. ofofthe DML COMMANDS DMLCOMMANDS COMMANDS DML
The above commands are all examples of DDL commands and thus commands that modify Theabove abovecommands commandsare areall allexamples examplesofofDDL DDLcommands commandsand andthus thuscommands commands thatmodify modify The the structure of the database. The main use of these commands are in scriptsthat that create the structure ofthe the database. The main use these commands arecommands, scriptsthat thatcreate create the structure database. The main ofofthese commands are ininscripts databases. Inofthis section I will show theuse syntax of the three DML and unlike databases. thissection section will showthe the syntax the three DML commands, andunlike unlike databases. InInthis I Iwill show syntax ofofthe DML DDL commands, these are commands that change thethree content of commands, the tables. and DDLcommands, commands,these theseare arecommands commandsthat thatchange changethe thecontent contentofofthe thetables. tables. DDL In this section and also in the rest of this appendix, it is assumed that the database books this sectionand and alsointroduction therest restofofand thisisappendix, appendix, assumed thatthe the databasebooks books InIn section ininthe this ititisis assumed that database arethis as described in also the loaded with data as described there. areasasdescribed describedininthe theintroduction introductionand andisisloaded loadedwith withdata dataasasdescribed describedthere. there. are
Download free eBooks at bookboon.com 159 159 159 159
JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA
Final examples examples FInal
will start start with with the the command command INSERT, INSERT, that that insert insert aa row row in in aa table. table. As As an an example, example, the the II will following command command inserts inserts aa row row in in the the author author table: table: following INSERT INTO author VALUES (186, 'Mogens', 'Trolle');
In executed, there there are are two two requirements: requirements: In order order that that the the command command can can be be executed, 1. 1. After After VALUES VALUES must must be be in in parentheses parentheses aa value value for for each each of of the the three three columns columns in in the the table table and and the the types types must must match. match. 2. The value of autnr (the value primary key key 2. The value of autnr (the value 186) 186) must must not not already already exist exist – – the the column column are are primary In In many many ways ways it it is is the the simplest simplest INSERT INSERT command, command, as as one one can can imagine. imagine. Often, Often, the the insertion insertion of of aa row, row, however, however, require require the the insertion insertion of of rows rows in in multiple multiple tables. tables. If If for example, I want to create the book for example, I want to create the book 78-7900-910-7, 78-7900-910-7, Afrikas Afrikas dyreliv dyreliv publiched publiched on on Globe Globe as as 1. 1. edition edition and and written written by by Mogens Mogens Trolle Trolle
Download free eBooks at bookboon.com 160 160
Click on the ad to read more
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
Final examples FInal FInal examples examples
then the publisher does not exists and must first be created. When the author isis already then then the the publisher publisher does does not not exists exists and and must must first first be be created. created. When When the the author author is already already created (with the command above), there must also be added a row to the table written created (with the command above), there must also be added a row to the table created (with the command above), there must also be added a row to the table written written and the book can be created asas follows: and the book can be created follows: and the book can be created as follows: INSERT INSERT INTO INTO publisher publisher VALUES VALUES (21, (21, 'Globe'); 'Globe'); INSERT INTO book book (isbn, (isbn, title, title, edition, edition, pubnr) pubnr) INSERT INTO VALUES ('87-7900-910-7', 'Afrikas dyreliv', VALUES ('87-7900-910-7', 'Afrikas dyreliv', 1, 1, 21); 21); INSERT INTO INTO written written VALUES VALUES ('87-7900-910-7', ('87-7900-910-7', 186); 186); INSERT
The first command requires no additional comments beyond again to be aware that publisher The Thefirst firstcommand commandrequires requiresno noadditional additionalcomments commentsbeyond beyondagain againto tobe beaware awarethat thatpublisher publisher number 21 must not already exist. number number 21 21 must must not not already already exist. exist. The second command does not insert values in all columns, and therefore you must specify The Thesecond secondcommand commanddoes doesnot notinsert insertvalues valuesin inall allcolumns, columns,and andtherefore thereforeyou youmust mustspecify specify in which columns to be inserted values. This is done by listing the column names in in which columns to be inserted values. This is done by listing the column names in which columns to be inserted values. This is done by listing the column names in in parentheses after the table name. Then VALUES must specify values for these columns. You parentheses parenthesesafter afterthe thetable tablename. name.Then ThenVALUES VALUESmust mustspecify specifyvalues valuesfor forthese thesecolumns. columns.You You should note note that that isbn isbn isis is necessary necessary because because itit it isis is the the primary primary key. key. Also Also the the title title isis is necessary, necessary, should should note that isbn necessary because the primary key. Also the title necessary, when this column defined NOT NULL and ok that there no value for year and when when this this column column isis is defined defined NOT NOT NULL NULL and and itit it isis is ok ok that that there there isis is no no value value for for year year and and pages, as the columns may contain NULL values. pubnr is defined NOT NULL, and pages, as the columns may contain NULL values. pubnr is defined NOT NULL, and you pages, as the columns may contain NULL values. pubnr is defined NOT NULL, and you you must indicate a publishing number, and when the column is a foreign key to the table must must indicate indicate aa publishing publishing number, number, and and when when the the column column isis aa foreign foreign key key to to the the table table publisher itit it must must be be aaa number number on on an an existing existing publishers. publishers. ItIt It isis is therefore therefore necessary, necessary, that that the the publisher publisher must be number on an existing publishers. therefore necessary, that the command that creates the publisher executed before the command that creates the book. command commandthat thatcreates createsthe thepublisher publisherisis isexecuted executedbefore beforethe thecommand commandthat thatcreates createsthe thebook. book. Note, finally, that there is not defined a category, although this column (column catnr) Note, finally, that there is not defined a category, although this column (column catnr) Note, finally, that there is not defined a category, although this column (column catnr) isis is a foreign key to the table category. It is not necessary, because the column allows NULL aa foreign foreign key key to to the the table table category. category. ItIt isis not not necessary, necessary, because because the the column column allows allows NULL NULL values, which which in in turn turn corresponds corresponds to, to, that that aaa book book does does not need to have category. values, values, which in turn corresponds to, that book does not not need need to to have have aaa category. category. Then there finally the last command, there not much to say, but you should note Then Then there there isis is finally finally the the last last command, command, asas as there there isis is not not much much to to say, say, but but you you should should note note that the two values is a composite key, and each part of the key is a foreign key, respectively that thatthe thetwo twovalues valuesisisaacomposite compositekey, key,and andeach eachpart partof ofthe thekey keyisisaaforeign foreignkey, key,respectively respectively to the the table table book book and and table table author. author. to to the table book and table author. The command UPDATE used to change the values in the columns, and by way of the The The command command UPDATE UPDATE isis is used used to to change change the the values values in in the the columns, columns, and and by by way way of of the the example, the following command updates a row in table book: example, example, the the following following command command updates updates aa row row in in table table book: book: UPDATE UPDATE book book SET SET year year = = '2010', '2010', pages pages = = 255 255 WHERE WHERE isbn isbn = = '87-7900-910-7'; '87-7900-910-7';
Download free eBooks at bookboon.com 161 161 161
JAVA 6: JAVA 6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
Final examples FInal examples FInal FInal examples examples
The command isis easy enough to understand. After SET follows a comma-separated list of The The command command is easy easy enough enough to to understand. understand. After After SET SET follows follows aa comma-separated comma-separated list list of of column names and values, where the values are the new values. Then there isis the WHERE column names and values, where the values are the new values. Then there the WHERE column names and values, where the values are the new values. Then there is the WHERE clause, which isis followed by aa condition that determines which rows to be modified. AA clause, clause, which which is followed followed by by a condition condition that that determines determines which which rows rows to to be be modified. modified. A WHERE clause can be extremely complex, which also will appear from the following about WHERE clause can be extremely complex, which also will appear from the following WHERE clause can be extremely complex, which also will appear from the following about about SELECT, but in this case it defines exactly one row. A WHERE may well define multiple SELECT, SELECT, but but in in this this case case it it defines defines exactly exactly one one row. row. A A WHERE WHERE may may well well define define multiple multiple rows, and where appropriate, all the rows that satisfy the condition are updated. You must rows, and where appropriate, all the rows that satisfy the condition are updated. You must rows, and where appropriate, all the rows that satisfy the condition are updated. You must specifically note that it is not a requirement that an UPDATE command has a WHERE specifically that an an UPDATE UPDATE command command has has aa WHERE WHERE specifically note note that that it it is is not not aa requirement requirement that part, and if not, all the table’s rows are updated. Also note that you can not change the part, and if not, all the table’s rows are updated. Also note that you can not change part, and if not, all the table’s rows are updated. Also note that you can not change the the value of the primary key. value value of of the the primary primary key. key. As another example the following command shows how to set value in aa column to NULL: As As another another example example the the following following command command shows shows how how to to set set value value in in a column column to to NULL: NULL: UPDATE book SET edition = NULL WHERE isbn = '87-7900-910-7'; UPDATE book SET edition = NULL WHERE isbn = '87-7900-910-7';
The command assumes of course that the column allows NULL values. The The command command assumes assumes of of course course that that the the column column allows allows NULL NULL values. values. Then there there is the DELETE DELETE command that that is used to to delete rows. rows. Suppose you you have Then Then there isis the the DELETE command command that isis used used to delete delete rows. Suppose Suppose you have have performed the following command: performed the following command: performed the following command: INSERT VALUES 'Test INSERT INTO INTO category VALUES (10, 'Test category'); category VALUES (10, 'Test category'); INSERT INTO
that inserts row in the table category. you want to delete the row again, you can do that that inserts inserts aaa row row in in the the table table category. category. IfIf If you you want want to to delete delete the the row row again, again, you you can can do do itit it in the following way: in in the the following following way: way: DELETE FROM category WHERE catnr = 10; DELETE DELETE FROM FROM category category WHERE WHERE catnr catnr = = 10; 10;
So simple to delete rows in table, but there are few things you should be aware So So itit it isis is simple simple to to delete delete rows rows in in aaa table, table, but but there there are are aaa few few things things you you should should be be aware aware of. First, the WHERE part can specify multiple rows, and if so all rows that satisfy the of. of. First, First, the the WHERE WHERE part part can can specify specify multiple multiple rows, rows, and and ifif so so all all rows rows that that satisfy satisfy the the condition after the WHERE clause are deleted. Moreover, it is allowed to completely omit condition condition after after the the WHERE WHERE clause clause are are deleted. deleted. Moreover, Moreover, itit isis allowed allowed to to completely completely omit omit the WHERE clause, and so, the command deletes all rows in the table. One should the the WHERE WHERE clause, clause, and and ifif if so, so, the the command command deletes deletes all all rows rows in in the the table. table. One One should should therefore be careful with DELETE, since it’s easy to delete more than the thought is. therefore therefore be be careful careful with with DELETE, DELETE, since since it’s it’s easy easy to to delete delete more more than than the the thought thought is. is. In this case, the table book has foreign key to the table category, and there book In In this this case, case, the the table table book book has has aaa foreign foreign key key to to the the table table category, category, and and ifif if there there isis is aaa book book that refers to the category with the key 10, the row not deleted. least the default, that that refers refers to to the the category category with with the the key key 10, 10, the the row row isis is not not deleted. deleted. ItIt It isis is atat at least least the the default, default, but there are other options. In the table book could have defined foreign key as follows: but defined foreign foreign key key as as follows: follows: but there there are are other other options. options. In In the the table table book book could could have have defined FOREIGN REFERENCES (catnr) DELETE NULL FOREIGN KEY KEY (catnr) REFERENCES category (catnr) ON DELETE SET NULL (catnr) REFERENCES category (catnr) ON DELETE SET NULL FOREIGN KEY
Download free eBooks at bookboon.com 162 162 162 162
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
Final examples FInal FInal examples examples
Where appropriate, the references with value 10 for catnr in the table book automatically Where Where appropriate, appropriate, the the references references with with value value 10 10 for for catnr catnr in in the the table table book book automatically automatically be set to NULL. Another option is to write: be set to NULL. Another option is to write: be set to NULL. Another option is to write: FOREIGN FOREIGN KEY KEY (catnr) (catnr) REFERENCES REFERENCES category category (catnr) (catnr) ON ON DELETE DELETE CASCACE CASCACE
If If so, so, the the rows rows of of the the table table book book that that refers refers to to the the number number in in the the category category table table will will also also be be deleted. deleted. Cascade Cascade can can be be important important for for ensuring ensuring the the integrity integrity of of the the database, database, but but there there is is still reason to warn a little against this clause. If you have defined foreign key catnr as ON still reason to warn a little against this clause. If you have defined foreign key catnr as ON DELETE DELETE CASCADE, CASCADE, and and you you performs performs the the command command DELETE DELETE FROM FROM category category WHERE WHERE catnr catnr == 1; 1;
then then you you deletes deletes not not only only aa row row in in the the table table category, category, but but you you also also deletes deletes all all rows rows in in the the table table book book that that refers refers to to this this row, row, and and that that is is the the vast vast majority majority (if (if not not som som of of them them are are prevented to be deleted by a foreign key in the table written). prevented to be deleted by a foreign key in the table written).
Download free eBooks at bookboon.com 163 163 163
Click on the ad to read more
JAVA 6: JAVA 6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
Final examples FInal examples FInal FInal examples examples
THE THE SELECT COMMAND THESELECT SELECTCOMMAND COMMAND THE SELECT COMMAND
Then there isisthe SELECT command, which absolutely is the command where there isismost Then Then there there is the the SELECT SELECT command, command, which which absolutely absolutely is is the the command command where where there there is most most to say. The simplest command you can think of isis aa command of the form: to say. The simplest command you can think of command of the form: to say. The simplest command you can think of is a command of the form: SELECT publisher; SELECT * FROM SELECT * * FROM publisher; FROM publisher;
which extracts all rows from the table publisher. means all columns and hence the result which which extracts all rows from the table publisher. A means all columns and hence the result whichextracts extractsall allrows rowsfrom fromthe thetable tablepublisher. publisher.AA A****means meansall allcolumns columnsand andhence hencethe theresult result consists of rows that should contain values from all columns. You can replace * with the consists of rows that should contain values from all columns. You can replace * with consists of rows that should contain values from all columns. You can replace * with the consists of rows that should contain values from all columns. You can replace * with the the names of the columns whose values you wants to show: names of the columns whose values you wants to show: names of the columns whose values you wants to show: SELECT FROM SELECT title, pages book; SELECT title, title, pages FROM book; pages FROM book;
SELECT can have WHERE part, where you specify the rows to extract: AA A SELECT SELECT can can have have aaa WHERE WHERE part, part, where where you you specify specify the the rows rows to to extract: extract: SELECT FROM SELECT title, title, pages pages FROM book book WHERE WHERE edition SELECT title, WHERE = 4; pages FROM book edition = 4;
The WHERE part can by using boolean operators to define more complex conditions: The WHERE part can by using boolean operators to define more complex conditions: The The WHERE WHERE part part can can by by using using boolean boolean operators operators to to define define more more complex complex conditions: conditions: SELECT SELECT title, pages FROM book SELECT title, title, pages pages FROM FROM book book WHERE (edition = 1 OR edition = AND > AND < WHERE (edition = 1 OR edition 3) pages 650 pages 700; = 3) AND pages > 650 AND pages < 700; WHERE (edition = 1 OR edition = 3) AND pages > 650 AND pages < 700;
also possible to specify substrings. As an example the following command extracts all ItIt It isis is also also possible possible to to specify specify substrings. substrings. As As an an example example the the following following command command extracts extracts all all rows where title starts with the word Java rows rows where where title title starts starts with with the the word word Java Java SELECT FROM WHERE title LIKE LIKE 'Java%'; 'Java%'; SELECT title, pages book SELECT title, title, pages FROM book WHERE title pages FROM book WHERE title LIKE 'Java%';
Download free eBooks at bookboon.com 164 164 164 164
JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA
Final FInal examples examples FInal examples examples FInal FInal examples examples FInal
while the following command extracts all rows where the title contains the word Java while the command all where title the Java while the the following following command command extracts extracts all all rows rows where where the the title title contains contains the the word word Java Java while while the following following command extracts extracts all rows rows where the the title contains contains the word word Java SELECT SELECT SELECT SELECT SELECT
title, title, title, title, title,
pages pages pages pages pages
FROM FROM FROM FROM FROM
book book book book book
WHERE WHERE WHERE WHERE WHERE
title title title title
LIKE LIKE LIKE LIKE
'%Java%'; '%Java%'; '%Java%'; '%Java%';
The rule is that % matches or more arbitrary characters. As another example extracts the The The rule rule is is that that % % matches matches 000 0 or or more more arbitrary arbitrary characters. characters. As As another another example example extracts extracts the the The rule is that % matches or more arbitrary characters. As another example extracts the The rule is that % matches 0 or more arbitrary characters. As another example extracts the command command command command command SELECT SELECT SELECT SELECT
title, title, title, title,
year, year, year, year,
pages pages pages pages
FROM FROM FROM FROM
book book book book
WHERE WHERE WHERE WHERE
year year year year
LIKE LIKE LIKE LIKE
'19__'; '19__'; '19__'; '19__';
all rows where the year (publisher year) starts with 19 and followed by two characters, all rows rows where where the the year year (publisher (publisher year) year) starts starts with with 19 19 and and isis is followed followed by by two two characters, characters, all all rows where the year (publisher year) starts with 19 and is followed by two characters, all rows where the year (publisher year) starts with 19 and is followed by two characters, since the rule is that _ exactly matches one character. since the the rule rule isis that that __ exactly exactly matches matches one one character. character. since since the rule is that _ exactly matches one character. The following command extracts the first three titles in the table book: The following following command command extracts extracts the the first first three three titles titles in in the the table table book: book: The The following command extracts the first three titles in the table The following command extracts the first three titles in the table book: book: SELECT SELECT SELECT SELECT
title title title title
FROM FROM FROM FROM
book book book book
LIMIT LIMIT LIMIT LIMIT
3; 3; 3; 3;
LIMIT can also be combined with WHERE: LIMIT can can also also be be combined combined with with aaa WHERE: WHERE: LIMIT LIMIT can can also also be be combined combined with with aa WHERE: WHERE: LIMIT SELECT SELECT SELECT SELECT SELECT
title title title title title
FROM FROM FROM FROM FROM
book book book book book
WHERE WHERE WHERE WHERE WHERE
edition edition edition edition edition
= == = =
2 22 2 2
LIMIT LIMIT LIMIT LIMIT LIMIT
3; 3; 3; 3; 3;
You should aware other systems of uses TOP. You should should be be aware aware that that other other database database systems systems instead instead of of LIMIT LIMIT uses uses SELECT SELECT TOP. TOP. You You should be be aware that that other database database systems instead instead of LIMIT LIMIT uses SELECT SELECT TOP. A SELECT can have an ORDER BY, where the rows are sorted according to values in SELECT can can have have an an ORDER ORDER BY, BY, where where the the rows rows are are sorted sorted according according to to values values in in aaa AA SELECT A SELECT can have an ORDER BY, where the rows are sorted according to values in A SELECT can have an the ORDER BY, command where the sorts rows the are rows sorted according to valuesorder: in aa particular column. Thus, following by title in ascending particular column. Thus, the following command sorts the rows by title in ascending order: particular particular column. column. Thus, Thus, the the following following command command sorts sorts the the rows rows by by title title in in ascending ascending order: order: particular column. Thus, the following command sorts the rows by title in ascending order: SELECT SELECT SELECT SELECT SELECT
isbn, isbn, isbn, isbn, isbn,
title title title title title
FROM FROM FROM FROM FROM
book book book book book
ORDER ORDER ORDER ORDER ORDER
BY BY BY BY BY
title; title; title; title; title;
If you wish that rows sorted descending one write: you wish wish instead instead that that the the rows rows are are sorted sorted in in descending descending order, order, one one can can write: write: IfIf If you you wish instead instead that the the rows are are sorted in in descending order, order, one can can write: SELECT SELECT SELECT SELECT SELECT
isbn, isbn, isbn, isbn, isbn,
title title title title title
FROM FROM FROM FROM FROM
book book book book book
ORDER ORDER ORDER ORDER ORDER
BY BY BY BY BY
title title title title title
DESC; DESC; DESC; DESC; DESC;
You can also sort by multiple criteria. Consider the following command, which extracts You can can also also sort sort by by multiple multiple criteria. criteria. Consider Consider the the following following command, command, which which extracts extracts You You can also sort by multiple criteria. Consider the following command, which extracts You can also sort by for multiple criteria. Consider thenumber following command, which extracts isbn, title and edition all rows where the category is 1, but so that the rows first isbn, title and edition for all rows where the category number is 1, but so that the rows first isbn, title and edition for all rows where the category number is 1, but so that the rows first isbn, title edition all rows the number isis 1, isbn, title and and edition for for allwithin rows where where the category category number 1, but but so so that that the the rows rows first first are sorted by edition, and each edition by the title: are sorted sorted by by edition, edition, and and within within each each edition edition by by the the title: title: are are are sorted sorted by by edition, edition, and and within within each each edition edition by by the the title: title: SELECT SELECT SELECT SELECT ORDER SELECT ORDER ORDER ORDER
isbn, title, edition isbn, title, title, edition edition isbn, isbn, title, edition BY edition, isbn, title, title; edition BY edition, title; BY edition, title; BY edition, title;
FROM FROM FROM FROM FROM
book book book book book
WHERE WHERE WHERE WHERE WHERE
catnr catnr catnr catnr catnr
= == = =
Download free eBooks at bookboon.com 165 165 165 165 165 165
1 11 1 1
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Final FInalexamples examples FInal examples
GROUP GROUPBY BY GROUP BY
For For aa SELECT SELECT you you can can also also define define GROUP GROUP BY, BY, which which indicates indicates that that the the result result should should For a SELECT you can also define GROUP BY, which indicates that the result should contain containone onerow rowfor foreach eachvalue valueininthe thecolumn columnthat thatwill willbe begrouped. grouped.For Forexample example contain one row for each value in the column that will be grouped. For example SELECT edition FROM book GROUP BY edition; SELECT edition FROM book GROUP BY edition;
thatwill will showall all editions.There There aresix six rowswith with thenumbers numbers 1, 2, 3, …,6.6.ItItisisnot not so that that willshow show alleditions. editions. Thereare are sixrows rows withthe the numbers1,1,2,2,3,3,…, …, 6. It is notso so interesting for the same result could be achieved in other ways, and GROUP BY has also interesting interestingfor forthe thesame sameresult resultcould couldbe beachieved achievedininother otherways, ways,and andGROUP GROUPBY BYhas hasalso also only of interest if you want to do something by the rows that fall within the individual only of interest if you want to do something by the rows that fall within the individual only of interest if you want to do something by the rows that fall within the individual groups.If, If, forexample example youwere were interestedinindetermining determining thesum sum of allpages pages distributed groups. groups. If,for for exampleyou you wereinterested interested in determiningthe the sumofofall all pagesdistributed distributed on edition you could use the command: on onedition editionyou youcould coulduse usethe thecommand: command: SELECT edition, SUM(pages) FROM book GROUP BY edition; SELECT edition, SUM(pages) FROM book GROUP BY edition;
93%
OF MIM STUDENTS ARE WORKING IN THEIR SECTOR 3 MONTHS FOLLOWING GRADUATION
MASTER IN MANAGEMENT • STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES THAT THE CAPITAL OF SPAIN OFFERS • PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR PROFESSIONAL GOALS • STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS EXPERIENCE
5 Specializations
Personalize your program
www.ie.edu/master-management
#10 WORLDWIDE MASTER IN MANAGEMENT FINANCIAL TIMES
[email protected]
Download free eBooks at bookboon.com 166 166 166
Length: 1O MONTHS Av. Experience: 1 YEAR Language: ENGLISH / SPANISH Format: FULL-TIME Intakes: SEPT / FEB
55 Nationalities
in class
Follow us on IE MIM Experience
Click on the ad to read more
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Final FInalexamples examples FInal examples
You Youshould shouldnote notethat thatthe theresult resultshows shows77rows. rows.This Thisisisbecause becausethere thereisisaabook bookininwhich whichthe the You should note that the result shows 7 rows. This is because there is a book in which the value valueofofedition editionisisNULL. NULL. value of edition is NULL. GROUP GROUPBY BYcan canbe becombined combinedwith withboth bothWHERE WHEREand andORDER ORDERBY, BY,and andthe theorder ordermust must GROUP BY can be combined with both WHERE and ORDER BY, and the order must be beasasshown shownbelow: below: be as shown below: SELECT edition, SUM(pages), SELECT edition, SUM(pages), WHERE pages < 1000 GROUP BY WHERE pages < 1000 GROUP BY
COUNT(*) FROM COUNT(*) FROM edition ORDER edition ORDER
book book BY edition DESC; BY edition DESC;
Hereisisselected selected thegroup group (theedition), edition), thesum sum of allpages pages withinthe the group,the the number Here Here is selectedthe the group(the (the edition),the the sumofofall all pageswithin within thegroup, group, thenumber number rowswithin withinthe thegroup, group,but butonly onlyfor forthe thebooks bookswhere wherethe thepage pagenumber numberisisless lessthan than1000: 1000: ofof rows of rows within the group, but only for the books where the page number is less than 1000:
WHEREclause clause defineswhich which rowstotobe be extracted,and and youcan can thereforethink think of the AA AWHERE WHERE clausedefines defines whichrows rows to beextracted, extracted, andyou you cantherefore therefore thinkofofthe the WHEREclause clauseasasaafilter filterthat thatfilters filtersthe therows. rows.Similarly Similarlywith withGROUP GROUPBY BYthere thereisisaaHAVING HAVING WHERE WHERE clause as a filter that filters the rows. Similarly with GROUP BY there is a HAVING clause,that that is a filterthat that specifieswhich which groupstotoinclude. include. Thesyntax syntax is as follows: clause, clause, thatisisaafilter filter thatspecifies specifies whichgroups groups to include.The The syntaxisisasasfollows: follows: SELECT edition, SUM(pages), COUNT(*) SELECT edition, SUM(pages), COUNT(*) WHERE pages < 1000 GROUP BY edition WHERE pages < 1000 GROUP BY edition HAVING edition = 2 OR edition = 4 OR HAVING edition = 2 OR edition = 4 OR
FROM book FROM book edition = 6 ORDER BY edition DESC; edition = 6 ORDER BY edition DESC;
Download free eBooks at bookboon.com 167 167 167
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA
Final examples FInal examples FInal examples examples FInal
where the HAVING clause specifies that only groups with a value of 2, 4 or 6 should be where the HAVING clause specifies that only groups with value of 2, or should be where the the HAVING HAVING clause clause specifies specifies that that only only groups groups with with aaa value value of of 2, 2, 44 4 or or 66 6 should should be be where extracted: extracted: extracted: extracted:
IfIf you execute the command you execute the command you execute execute the the command command IfIf you SELECT FROM book; edition SELECT edition edition FROM FROM book; book; SELECT
you get shown all editions, and there are 87 rows. This means that the same value appears you get shown all editions, and there are 87 rows. This means that the same value appears you get get shown shown all all editions, editions, and and there there are are 87 87 rows. rows. This This means means that that the the same same value value appears appears you several times. If you do not want that, you can write several times. you do not want that, you can write several times. times. IfIf If you you do do not not want want that, that, you you can can write write several SELECT edition book; DISTINCT FROM SELECT DISTINCT DISTINCT edition edition FROM FROM book; book; SELECT
which simply means that all rows must be different. which which simply simply means means that that all all rows rows must must be be different. different. JOIN JOIN JOIN
also possible to perform SELECT command that extracts rows from multiple tables, ItIt It isis is also also possible possible to to perform perform aaa SELECT SELECT command command that that extracts extracts rows rows from from multiple multiple tables, tables, and we often talk about JOIN. As an example shown JOIN command, that extracts and and we we often often talk talk about about aaa JOIN. JOIN. As As an an example example isis is shown shown aaa JOIN JOIN command, command, that that extracts extracts the title from the book table and the name from the publishers table, but such that there the the title title from from the the book book table table and and the the name name from from the the publishers publishers table, table, but but such such that that there there only are extracted a row where the value in column pubnr is similar in the two tables: only only are are extracted extracted aa row row where where the the value value in in column column pubnr pubnr isis similar similar in in the the two two tables: tables: SELECT name book, WHERE publisher.pubnr; title, FROM publisher book.pubnr SELECT title, title, name name FROM FROM book, book, publisher publisher WHERE WHERE book.pubnr book.pubnr == = publisher.pubnr; publisher.pubnr; SELECT
Put slightly differently, so are each row of the book table combined with each row in the Put Put slightly slightly differently, differently, so so are are each each row row of of the the book book table table combined combined with with each each row row in in the the publisher table, but only rows with same value in the columns for pubnr are included in publisher publisher table, table, but but only only rows rows with with same same value value in in the the columns columns for for pubnr pubnr are are included included in in the result. The result has then 87 rows with two columns. You should note that the two the the result. result. The The result result has has then then 87 87 rows rows with with two two columns. columns. You You should should note note that that the the two two columns names title and name are unique determined in the combination of the two tables columns columns names names title title and and name name are are unique unique determined determined in in the the combination combination of of the the two two tables tables but both tables has a column named pubnr, and therefore it is necessary to qualify the name but but both both tables tables has has aa column column named named pubnr, pubnr, and and therefore therefore itit isis necessary necessary to to qualify qualify the the name name with the table name in the WHERE part. with with the the table table name name in in the the WHERE WHERE part. part. you do not specify concrete columns in join such as IfIf If you you do do not not specify specify concrete concrete columns columns in in aaa join join such such as as SELECT FROM publisher book.pubnr publisher.pubnr; book, WHERE SELECT ** * FROM FROM book, book, publisher publisher WHERE WHERE book.pubnr book.pubnr == = publisher.pubnr; publisher.pubnr; SELECT
Download free eBooks at bookboon.com 168 168 168 168
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS
Final FInalexamples examples
the theresult resultisisstill stillthe the87 87rows, rows,but butallallcolumns columnsfrom fromboth bothtables tablesisisthere there
Note Noteespecially especiallythat thatthe thecolumn columnpubnr pubnrisisthere theretwice. twice. There Thereare areseveral severaltypes typesofofJOIN JOINon ontables, tables,and andan anexample exampleasasthe theabove aboveisiscalled calledan anINNER INNER JOIN and can also be written as follows: JOIN and can also be written as follows: SELECT title, name FROM book INNER JOIN publisher ON book.pubnr = publisher.pubnr;
DO YOU WANT TO KNOW:
What your staff really want?
The top issues troubling them?
How to retain your top staff FIND OUT NOW FOR FREE
How to make staff assessments work for you & them, painlessly?
Get your free trial Because happy staff get more done
Download free eBooks at bookboon.com 169 169
Click on the ad to read more
JAVA JAVA6: 6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Final FInalexamples examples FInal examples
An An INNER INNER JOIN JOIN between between two two tables tables returns returns rows rows in in which which there there are are matches matches in in both both tables. tables. An An INNER INNER JOIN JOIN (and (and all all other other JOIN JOIN operations) operations) can can also also be be combined combined with with aa WHERE WHERE clause clause asas such such SELECT title, name FROM book INNER JOIN category ON book.catnr = category.catnr WHERE isbn LIKE '87-%';
that that returns returns the the title title and and category category name name for for the the books books where where isbn isbn starts starts with with 8787- (all (all Danish Danish titles): titles):
In In addition addition to to INNER INNER JOIN, JOIN, there there are are the the following following JOIN JOIN operations: operations: --- LEFT LEFT JOIN, JOIN, which which returns returns all all rows rows from from the the left left table, table, even even ifif there there isis no no match match in in the the right right table. table. --- RIGHT RIGHT JOIN, JOIN, which which returns returns all all rows rows of of the the right right table, table, even even ifif there there isis no no match match in in the the left left table. table. --- FULL FULLJOIN, JOIN,which whichreturns returnsall allrows rowseven evenififthere thereisisno nomatch matchin inone oneof ofthe thetwo twotables. tables. --- CARTESIAN CARTESIAN JOIN, JOIN, that that returns returns the the cartesian cartesian product product of of the the two two tables. tables. You You should should be be aware aware that that aa FULL FULL JOIN JOIN isis not not supported supported by by MySQL. MySQL. As As an an example example II will will show show aa LEFT LEFT JOIN: JOIN: SELECT title, name FROM book LEFT JOIN category ON book.catnr = category.catnr WHERE isbn LIKE '87-%';
Note that that in in principle principle itit isis the the same same JOIN JOIN asas above, above, but but this this time time the the result result shows shows seven seven Note rows. This This isis because because the the book book table table has has aa row, row, which which isis NULL NULL in in the the column column catnr catnr and and rows. therefore does does not not match match aa row row in in the the category category table, table, but but itit isis included included in in the the result result asas therefore opposed to to an an INNER INNER JOIN JOIN where where there there must must be be aa match match in in both both tables. tables. opposed
Download free eBooks at bookboon.com 170 170 170
JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Final FInal examples examples FInal examples FInal examples
Below Below isis aa RIGHT RIGHT JOIN: JOIN: Below is a RIGHT Below is a RIGHT JOIN: JOIN: SELECT title, name FROM book RIGHT JOIN category SELECT title, name FROM book RIGHT JOIN category SELECT title, = name FROM book RIGHT JOIN category ON book.catnr category.catnr ON book.catnr = category.catnr ON book.catnr = '87-%'; category.catnr WHERE isbn LIKE WHERE isbn LIKE '87-%'; WHERE isbn LIKE '87-%';
ItIt also also shows shows 66 rows rows (that (that isis the the same same result result as as the the corresponding corresponding INNER INNER JOIN) JOIN) because because It also shows 6 rows (that is the same result as the corresponding INNER JOIN) because the table category does not aa value column which not match It also shows 6 rows is therows samewith result as thein JOIN) the table category does(that not have have rows with value incorresponding column catnr, catnr,INNER which does does notbecause match the table category does not have rows with a value in column catnr, which does not match aathe row in the book table. table category does not have rows with a value in column catnr, which does not match row in the book table. aa row in the book table. row in the book table. The The next next command command isis again again an an example example of of aa INNER INNER JOIN: JOIN: The next command is again an example of a INNER The next command is again an example of a INNER JOIN: JOIN: SELECT title, name SELECT title, name SELECT book.pubnr title, name WHERE = WHERE book.pubnr = WHERE book.pubnr =
FROM book, publisher FROM book, publisher FROM book, publisher publisher.pubnr AND isbn LIKE '87-%'; publisher.pubnr AND isbn LIKE '87-%'; publisher.pubnr AND isbn LIKE '87-%';
and and the the result result isis 77 rows. rows. IfIf you you delete delete the the JOIN JOIN condition, condition, you you get get aa CARTESIAN CARTESIAN JOIN: JOIN: and the result is 7 rows. If you delete the JOIN condition, you get a CARTESIAN and the result is 7 rows. If you delete the JOIN condition, you get a CARTESIAN JOIN: JOIN: SELECT title, name FROM book, publisher WHERE isbn LIKE '87-%'; SELECT title, name FROM book, publisher WHERE isbn LIKE '87-%'; SELECT title, name FROM book, publisher WHERE isbn LIKE '87-%';
and the the result result isis 147 147 rows. rows. The The reason reason isis that that each each row row of of the the table table book book (there (there are are 77 meeting meeting and and the result is 147 rows. The reason is that each row of the table book (there are 7 and WHERE the result clause) is 147 rows. The reason isall that each row of the table book (thereisare 7 meeting meeting the is combined with rows in the publisher table (which 21), and the the the WHERE clause) isis combined with all rows in the publisher table (which isis 21), and the WHERE clause) combined with all rows in the publisher table (which 21), and the the WHERE clause) is combined with all rows in the publisher table (which is 21), and the result isis aa total total of of 77 ×× 21 21 == 147 147 rows. rows. result result is a total of 7 × 21 = 147 rows. result is a total of 7 × 21 = 147 rows. also possible possible to to join join more more than than two two tables. tables. The The following following command command isis aa JOIN JOIN between between ItIt isis also It is also possible to join more than two tables. The following command is a JOIN between It is also possible to join more than two tables. The starts following command iswith a JOIN between three tables showing for each title, where the isbn with 87 a row the title and three tables showing for each title, where the isbn starts with 87 aa row with the title and three tables showing for each title, where the isbn starts with 87 row with the title and three tables showing for each title, where the isbn starts with 87 a row with the title and author’s name name (one (one row row for for each each author): author): author’s author’s name (one row for each author): author’s name (one row for each author): SELECT title, firstname, lastname FROM book SELECT title, firstname, lastname FROM book SELECT JOIN title, firstname, lastname =FROM book INNER written ON book.isbn written.isbn INNER JOIN written ON book.isbn = written.isbn written ON ON written.autnr book.isbn = written.isbn INNER JOIN author = author.autnr INNER JOIN author ON written.autnr = author.autnr INNER book.isbn JOIN author ON '87-%'; written.autnr = author.autnr WHERE LIKE WHERE book.isbn LIKE '87-%'; WHERE book.isbn LIKE '87-%';
By combining (join) book and written you get for each book the author numbers for the By combining (join) book and written you get for each book the author numbers for the By and you get author for By combining combining (join) book and written written you get for for each each book the author numbers for the the book’s authors,(join) and book by combining this result with thebook tablethe author younumbers can obtain the book’s authors, and by combining this result with the table author you can obtain the book’s authors, and by combining this result with the table author you can obtain the book’s authors, and by combining this result with the table author you can obtain the authors’ names. The command in question can also be written as follows: authors’ names. The command in question can also be written as follows: authors’ authors’ names. names. The The command command in in question question can can also also be be written written as as follows: follows: SELECT title, firstname, lastname FROM book, written, author SELECT title, firstname, lastname FROM book, written, author SELECT book.isbn title, firstname, lastname FROM book, written, author WHERE = written.isbn AND written.autnr = author.autnr WHERE book.isbn = written.isbn AND written.autnr = author.autnr WHERE book.isbn = written.isbn AND written.autnr = author.autnr AND book.isbn LIKE '87-%'; AND book.isbn LIKE '87-%'; AND book.isbn LIKE '87-%';
Download free eBooks at bookboon.com 171 171 171 171
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
Final examples FInal FInal examples examples
JAVA 6: JDBC AND DATABASE APPLICATIONS
FInal examples
As another example, shows the following command isbn and title ofofallallmathematics books As As another another example, example, shows shows the the following following command command isbn isbn and and title title of all mathematics mathematics books books published by Prentice Hall: published by Prentice Prentice Hall:the following command isbn and title of all mathematics books As another example, shows published by Hall: published by Prentice Hall: SELECT SELECT isbn, isbn, title title FROM FROM book, book, category, category, publisher publisher WHERE book.catnr = category.catnr AND book.pubnr WHERE book.catnr category.catnr AND book.pubnr = publisher.pubnr publisher.pubnr SELECT isbn, title= FROM book, category, publisher = AND category.name LIKE '%Matematik%' AND category.name '%Matematik%' WHERE book.catnr = LIKE category.catnr AND book.pubnr = publisher.pubnr AND publisher.name LIKE '%Prentice AND category.name publisher.nameLIKE LIKE'%Matematik%' '%Prentice Hall%'; Hall%'; AND AND publisher.name LIKE '%Prentice Hall%';
As appears from the JOIN operations NULL values can sometimes lead unexpected As Asappears appearsfrom fromthe theJOIN JOINoperations operationsNULL NULLvalues valuescan cansometimes sometimeslead leadtoto tounexpected unexpected results. Although ithas has nothing todo dowith with joins, please note thefollowing following syntax results. Although nothing toto joins, please note the syntax As appears from it the JOIN operations NULL values can sometimes lead to unexpected results. Although it has nothing do with joins, please note the following syntax results. Although it has nothing to do with joins, please note the following syntax SELECT SELECT * * FROM FROM book book WHERE WHERE edition edition IS IS NULL; NULL; SELECT * FROM book WHERE edition IS NULL;
which which returns returns all all books books whose whose value value for for edition edition is is NULL. NULL. Similarly, Similarly, one one can can write write which returns all books whose value for edition is NULL. Similarly, one can which returns all books whose value for edition is NULL. Similarly, one can write write SELECT * * FROM FROM book book WHERE WHERE edition edition IS IS NOT NOT NULL; NULL; SELECT SELECT * FROM book WHERE edition IS NOT NULL;
Challenge the way we run
EXPERIENCE THE POWER OF FULL ENGAGEMENT… RUN FASTER. RUN LONGER.. RUN EASIER…
READ MORE & PRE-ORDER TODAY WWW.GAITEYE.COM
1349906_A6_4+0.indd 1
22-08-2014 12:56:57
Download free eBooks at bookboon.com 172 172 172
Click on the ad to read more
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
Final examples FInal FInal examples examples
When Whenyou youjoins joinsseveral severaltables tablesthat thatcan canoccur occurname namematches matcheswhere wheretwo twocolumns columnshas hasthe thesame same name. As shown above, one can solve this problem by qualifying the name with the table name. As shown above, one can solve this problem by qualifying the name with the table name. name.ItItcan canlead leadtotoaasomewhat somewhatclumsy clumsysyntax, syntax,and andadditionally, additionally,ititmay maymean meanthat thatthere thereare are two columns in the result, with the same name. To solve these problems, you can use the two columns in the result, with the same name. To solve these problems, you can use the concept conceptofofan analias, alias,where whereyou youcan cangive giveaatable tableororaacolumn columnaacustom customname. name.The Thefollowing following command determines the title, publisher name and category name for all Danish books: command determines the title, publisher name and category name for all Danish books: SELECT title AS Text, P.name AS 'Publisher name', C.Name AS 'Category name' FROM book AS B, publisher AS P, category AS C WHERE B.pubnr = P.pubnr AND B.catnr = C.catnr AND isbn LIKE '87-%';
Thereisisextracted extracteddata datafrom fromthree threetables: tables:book, book,publisher publisherand andcategory, category,but butthese thesetables tablesare are There assignednames namesB,B,PPand andC. C.InInaddition additionare areeach eachofofthe thethree threecolumns columnsassigned assignedaaname, name, assigned and andyou youshould shouldnote notethat thatthis thisnames namesare areused usedininthe theresult: result:
SETOPERATIONS SET OPERATIONS
twoSELECT SELECTcommands commandsare areunion unioncompatible, compatible,that thatisisthey theyresults resultsininthe thesame samenumber numberofof IfIftwo columns,columns columnsofofthe thesame sametypes, types,and andthe thecolumns columnsininthe thesame sameorder, order,one onecan canperform perform columns, the theUNION: UNION: SELECT UNION SELECT
isbn, title, edition FROM book WHERE isbn LIKE '87-%' isbn, title, edition FROM book WHERE edition = 3 OR edition = 4;
The first first command command returns returns 77 rows rows and and the the second second 11 11 rows. rows. Because Because UNION UNION removes removes The duplicate duplicaterows, rows,and andthere thereare aretwo tworows rowsthat thatare areidentical, identical,the thecommand commandwill willresult resultinin16 16 rows. rows.IfIfyou youinstead insteadwrites writes SELECT isbn, UNION ALL SELECT isbn,
title, edition FROM book WHERE isbn LIKE '87-%' title, edition FROM book WHERE edition = 3 OR edition = 4;
are duplicate rows retained, and the command will result in 18 rows. are duplicate rows retained, and the command will result in 18 rows.
Download free eBooks at bookboon.com 173 173 173
JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
Final FInal examples examples
Instead Instead of of UNION UNION you you can can write write INTERSECT, INTERSECT, and and the the result result is is the the intersection. intersection. This This clause clause is is not not supported supported by by MySQL. MySQL. It It is is also also possible possible to to write write EXCEPT EXCEPT that that means means set set difference, but this clause is not supported by MySQL. difference, but this clause is not supported by MySQL. SQL SQL FUNCTIONS FUNCTIONS
As As part part of of SQL SQL are are aa number number of of functions functions that that can can be be used used in in SQL SQL commands. commands. Above Above II have have already already used used the the SUM() SUM() and and COUNT(). COUNT(). The The following following is is aa listing listing of of the the most most important important of of those those functions, functions, and and there there are are many, many, but but they they can can be be divided divided into into groups: groups: 1. 1. general general functions functions 2. 2. numeric numeric functions functions 3. 3. functions functions to to strings strings 4. functions to date 4. functions to date and and time time and and in in addition addition there there is is aa (sometimes (sometimes large) large) number number of of functions, functions, depending depending on on the the database database product. product. GENERAL GENERAL FUNCTIONS FUNCTIONS
This This group group of of functions functions include: include: -----------
COUNT COUNT MAX MAX MIN MIN SUM SUM AVG AVG
and and are are the the classic classic functions, functions, where where II above above has has used used COUNT COUNT and and SUM. SUM. As As an an example example determines the following command the number of books, the total number of pages determines the following command the number of books, the total number of pages (total (total number number of of pages pages of of all all the the books), books), the the average average number number of of pages, pages, the the smallest smallest number number of of pages pages and and the the largest largest number number of of pages: pages: SELECT COUNT(*), SUM(pages), AVG(pages), MIN(pages), MAX(pages) FROM book;
Download free eBooks at bookboon.com 174 174
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS
Final FInalexamples examples
NUMERIC NUMERICFUNCTIONS FUNCTIONS
ABS ACOS ASIN ABS ACOS ASIN BIT_COUNT BIT_OR CEIL BIT_COUNT BIT_OR CEIL COT DEGREES COT DEGREES EXP EXP INTERVAL LEAST LOG INTERVAL LEAST LOG PI POW POWER PI POW POWER SIN SQRT STD SIN SQRT STD
ATAN ATAN2 BIT_AND ATAN ATAN2 BIT_AND CEILING CONV COS CEILING CONV COS FLOOR FORMAT GREATEST FLOOR FORMAT GREATEST LOG10 MOD OCT LOG10 MOD OCT RADIANS RAND ROUND RADIANS RAND ROUND STDDEV TAN TRUNCATE STDDEV TAN TRUNCATE
The The meaning meaning ofof most most ofof the the functions functions isis indicated indicated by by the the name, name, and and you you can can not not be be sure that all database systems implements all this functions. Consider as an example the sure that all database systems implements all this functions. Consider as an example the following followingstatements: statements: SET @my = 0; SELECT @my := AVG(pages) FROM book; SELECT RAND(), PI(), SQRT(2), STDDEV(pages), SQRT(SUM((pages – @my) * (pages – @my)) / COUNT(*)) AS Sigma FROM book;
This e-book is made with
SETASIGN
SetaPDF
PDF components for PHP developers
www.setasign.com Download free eBooks at bookboon.com 175 175
Click on the ad to read more
JAVA JAVA6: 6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS
Final FInalexamples examples
Here Here are are the the results results of of the the first first three three functions functions simple simple enough, enough, while while the the fourth fourth function function determines the standard-deviation of the books pages. The first statement defines a determines the standard-deviation of the books pages. The first statement defines a variable variable and the next statement set this variable equal to the average (mean value) of the number and the next statement set this variable equal to the average (mean value) of the number of of pages. The value of this variable is used in the last formula, which calculates the standard pages. The value of this variable is used in the last formula, which calculates the standard deviation deviation of of the the number number pages. pages. ItIt isis of of course course no no reason reason for for that that calculation, calculation, because because there there isis aa function STDDEV that do the same, but the example should partly show how function STDDEV that do the same, but the example should partly show how you you can use a variable and partly an example of a complex expression. can use a variable and partly an example of a complex expression. FUNCTIONS FUNCTIONSTO TOSTRINGS STRINGS
ASCII BIN BIN_LENGTH ASCII BIN BIN_LENGTH CHAR_LENGTH CHARACTER_LENGTH CONCAT_WS CHAR_LENGTH CHARACTER_LENGTH CONCAT_WS CONCAT CONV ELT CONCAT CONV ELT EXPORT_SET FIELD FIND_IN_SET EXPORT_SET FIELD FIND_IN_SET FORMAT HEX INSERT FORMAT HEX INSERT INSTR LCASE LEFT INSTR LCASE LEFT LENGTH LOAD_FILE LOCATE LENGTH LOAD_FILE LOCATE LOWER LPAD LTRIM LOWER LPAD LTRIM MAKE_SET MID OCT MAKE_SET MID OCT OCTET_LENGTH ORD POSITION OCTET_LENGTH ORD POSITION QUOTE REGEXP REPEAT QUOTE REGEXP REPEAT REPLACE REVERT RIGHT REPLACE REVERT RIGHT RPAD RTRIM SOUNDEX RPAD RTRIM SOUNDEX SOUNDEX_LIKE SPACE STRCMP SOUNDEX_LIKE SPACE STRCMP SUBSTR SUBSTRING SUBSTRING_INDEX SUBSTR SUBSTRING SUBSTRING_INDEX TRIM UCASE UNHEX TRIM UCASE UNHEX UPPER UPPER Most Most of of the the functions functions are are easy easy enough enough to to understand, understand, but but not not all, all, and and there there itit isis necessary necessary to look up the meaning for the function. As an example determines the following statement to look up the meaning for the function. As an example determines the following statement the the title’s title’s length length and and the the first first 10 10 characters characters in in the the title title of of all all books books whose whose title title contains contains the the word word Java: Java: SELECT LENGTH(title), SUBSTR(title, 1, 10) FROM book WHERE title LIKE '%Java%';
Download free eBooks at bookboon.com 176 176
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS
Final FInalexamples examples
FUNCTIONS FUNCTIONSTO TODATE DATEAND ANDTIME TIME
As Asdiscussed discussedabove, above,SQL SQLtypes typesfor fordates datesclould clouldbe bedifficult difficulttotouse usecorrect, correct,and andthere thereare areaa number numberofoffunctions functionsthat thatspecifically specificallyare areused usedfor fordates: dates: ADD_DATE ADD_TIME CONVERT_TZ ADD_DATE ADD_TIME CONVERT_TZ CURDATE CURRENT_DATE CURRENT_TIME CURDATE CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURTIME DATE_ADD CURRENT_TIMESTAMP CURTIME DATE_ADD DATE_FORMAT DATE_SUB DATE DATE_FORMAT DATE_SUB DATE DATE_DIFF DAY DAYNAME DATE_DIFF DAY DAYNAME DAYOFMONTH DAYOFWEEK DAYOFYEAR DAYOFMONTH DAYOFWEEK DAYOFYEAR EXTRACT FROM_DAYS FROM_UNIXTIME EXTRACT FROM_DAYS FROM_UNIXTIME HOUR LAST_DAY LOCALTIME HOUR LAST_DAY LOCALTIME LOCALTIMESTAMP MAKEDATE MAKETIME LOCALTIMESTAMP MAKEDATE MAKETIME MICROSECOND MINUTE MONTH MICROSECOND MINUTE MONTH MONTHNAME NOW PERIOD_ADD MONTHNAME NOW PERIOD_ADD PERIOD_DIFF QUATER SEC_TO_TIME PERIOD_DIFF QUATER SEC_TO_TIME SECOND STR_TO_DATE SUBDATE SECOND STR_TO_DATE SUBDATE SUBTIME SYSDATE TIME_FORMAT SUBTIME SYSDATE TIME_FORMAT TIME_TO_SEC TIME TIMEDIFF TIME_TO_SEC TIME TIMEDIFF TIMESTAMP TIMESTAMPADD TIMESTAMPDIFF TIMESTAMP TIMESTAMPADD TIMESTAMPDIFF TO_DAYS UNIX_TIMESTAMP UTC_DATE TO_DAYS UNIX_TIMESTAMP UTC_DATE UTC_TIME UTC_TIMESTAMP WEEK UTC_TIME UTC_TIMESTAMP WEEK WEEK_DAY WEEKOFYEAR YEAR WEEK_DAY WEEKOFYEAR YEAR YEARWEEK YEARWEEK As Asthe thetable tableshows, shows,there thereare aremany manyfunctions functionsand andititisisnot notsosoeasy easytotofigure figureout outthe themeaning meaning ofofall allofofthem, them,but butthe theresult resultisisthat thatthere thereare aremany manyopportunities opportunitiestotomanipulate manipulatedate dateand and time timeininSQL. SQL.As Asaasmall smallexample, example,the thefollowing followingstatement statementuse usetwo twoofofthis thisfunctions: functions: SET @d = CURDATE(); SET @t = CURTIME(); SELECT @d, @T;
Download free eBooks at bookboon.com 177 177
Deloitte & Touche LLP and affiliated entities.
JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
Final FInal examples examples
VIEW’S VIEW’S
AA view view isis basically basically nothing nothing more more than than aa SQL SQL statement statement that that isis stored stored in in the the database, database, but but itit can can be be seen seen as as aa form form of of virtual virtual table, table, as as you you in in principle principle can can use use itit in in the the same same way, way, as as you you uses uses other other tables. tables. AA view view can can be be created created on on basis basis of of one one or or more more tables, tables, but but what what you you can do with a view is determined by how it is created. The purpose of a view is can do with a view is determined by how it is created. The purpose of a view is to to structure structure the the content content of of aa database database corresponding corresponding to to the the users’ users’ use use of of the the database database limiting limiting access access to to the the data data that that users users can can work work with with allowing allowing data data from from multiple multiple tables tables to to appear appear as as aa single single table table In In MySQL MySQL Workbench Workbench you you can can create create aa view view by by right-click right-click on on Views Views (the (the tab tab SCHEMA) SCHEMA) and choose Create View. You then gets the following skeleton: and choose Create View. You then gets the following skeleton: CREATE VIEW 'new_view' AS
360° thinking
.
360° thinking
.
360° thinking
.
Discover the truth at www.deloitte.ca/careers
© Deloitte & Touche LLP and affiliated entities.
Discover the truth at www.deloitte.ca/careers
© Deloitte & Touche LLP and affiliated entities.
Discoverfree theeBooks truth atatbookboon.com www.deloitte.ca/careers Download
Click on the ad to read more
178 178
Dis
JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Final FInal examples examples FInal examples
As As an an example, example, you you can can write write the the following following view: view: As an example, you can write the following view: CREATE VIEW Prentice_hall AS SELECT isbn, title, edition, year, pages CREATE VIEW Prentice_hall FROM book WHERE pubnr = 2;AS SELECT isbn, title, edition, year, pages FROM book WHERE pubnr = 2;
which defines defines aa view view called called Prentice_hall Prentice_hall that that for for all all books books where where pubnr pubnr are are 22 extracts extracts the the which which defines a view called Prentice_hall that for all books where pubnr are 2 extracts the isbn, isbn, title, title, edition, edition, year year and and pages. pages. That That isis the the view view of of columns columns in in the the table table book book of of all all books books isbn, title, edition, year and That is then the columns in theWorkbench table book of all books Hall.pages. When you thenview clickofApply, Apply, MySQL Workbench creates the published When you click MySQL creates the published by by Prentice Prentice Hall. published by Prentice Hall. When you then click Apply, MySQL Workbench creates the following following view: view: following view: CREATE CREATE ALGORITHM = UNDEFINED ALGORITHM UNDEFINED DEFINER = = 'pa'@'%' DEFINER = 'pa'@'%' SQL SECURITY DEFINER SQL SECURITY DEFINER VIEW 'books'.'Prentice_hall' AS VIEW 'books'.'Prentice_hall' AS SELECT SELECT 'books'.'book'.'isbn' AS 'isbn', 'books'.'book'.'isbn' 'books'.'book'.'title' AS AS 'isbn', 'title', 'books'.'book'.'title' AS 'title', 'books'.'book'.'edition' AS 'edition', 'books'.'book'.'edition' 'edition', 'books'.'book'.'year' AS AS 'year', 'books'.'book'.'year' AS 'year', 'books'.'book'.'pages' AS 'pages' 'books'.'book'.'pages' AS 'pages' FROM FROM 'books'.'book' 'books'.'book' WHERE WHERE ('books'.'book'.'pubnr' = 2) ('books'.'book'.'pubnr' = 2)
This view may then be used in the same way as the other tables, and for example you This view may then be used in the same way as the other tables, and for example you can Thiswrite: view may then be used in the same way as the other tables, and for example you can write: can write: SELECT * FROM Prentice_hall; SELECT * FROM Prentice_hall;
Indeed, Indeed, one one can can also also to to some some extent extent perform perform SQL SQL INSERT, INSERT, UPDATE UPDATE and and DELETE DELETE Indeed, one can also to some extent perform SQL INSERT, UPDATE and DELETE statements statements in in aa view. view. Consider Consider as as an an example example the the following following view, view, which which extracts extracts first first and and statements in a view. Consider as an example the following view, which extracts first and last last names names of of all all authors authors where where the the last last name name starts starts with with aa K: K: last names of all authors where the last name starts with a K: CREATE VIEW CREATE VIEW FROM author FROM author
knames AS SELECT DISTINCT firstname, lastname knames lastname AS SELECT DISTINCT WHERE LIKE 'K%'; firstname, lastname WHERE lastname LIKE 'K%';
If you then performs the statement IfIf you you then then performs performs the the statement statement SELECT * FROM knames; SELECT * FROM knames;
Download free eBooks at bookboon.com 179 179 179
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Final FInalexamples examples FInal examples
JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA
FInal examples examples FInal
you will see that the view contains 8 rows. If you then performs the following statements: you you will will see see that that the the view view contains contains 8 8 rows. rows. If If you you then then performs performs the the following following statements: statements: you will see that the view contains 8 rows. If you then performs the following you will see that the view contains 8 rows. If you then performs the following statements: statements: INSERT INSERT select INSERT select INSERT select select
INTO INTO author author VALUES VALUES * from knames; INTO author * from knames; INTO author VALUES VALUES * * from from knames; knames;
(187, (187, (187, (187,
'Poul', 'Poul', 'Poul', 'Poul',
'Klausen'); 'Klausen'); 'Klausen'); 'Klausen');
you will see that the view knames now has rows. This means that after the table author you you will will see see that that the the view view knames knames now now has has 99 9 rows. rows. This This means means that that after after the the table table author author is updated is also the view updated. will see that view knames now has 9 rows. This means that after the table isyou updated is also the view updated. you will seeis that author is updated also the view view knames updated.now has 9 rows. This means that after the table author is is updated updated is is also also the the view view updated. updated. Next, if you try: Next, Next, ifif you you try: try: Next, if if you you try: try: Next, INSERT INSERT INSERT INSERT
INTO INTO INTO INTO
knames knames knames knames
VALUES VALUES VALUES VALUES
('Jens', ('Jens', ('Jens', ('Jens',
'Kristensen'); 'Kristensen'); 'Kristensen'); 'Kristensen');
you you get get an an error error where where you you are are told told that that the the parent parent table table can can not not be be updated. updated. Of Of course course it it you get an error where you are told that the parent table can not be updated. Of course itit is not so strange, because there is not enough information (there is not an author number) you get an error where you are told that the parent table can not be updated. Of course you error where you are is told the parent table can notisbenot updated. Of number) course it is notgetsoan strange, because there notthat enough information (there an author isis not so strange, because there isisnot enough information (there isisnot an author number) to create a row in the author table. Consider the following view: not so strange, because there not enough information (there not an author number) is so strange, theretable. is notConsider enough the information to not create a row inbecause the author following(there view: is not an author number) to create aa row in the author table. Consider the following view: to create row in the author table. Consider the following to create a row in the author table. Consider the following view: view: CREATE CREATE VIEW VIEW FROM author CREATE FROM author CREATE VIEW VIEW FROM author author FROM
lnames lnames AS AS SELECT SELECT autnr, autnr, firatname, firatname, WHERE lastname LIKE 'L%'; lnames AS SELECT autnr, WHERE lastname LIKE 'L%'; lnames AS SELECT autnr, firatname, firatname, WHERE lastname lastname LIKE LIKE 'L%'; 'L%'; WHERE
INSERT INSERT INSERT INSERT
lnames lnames lnames lnames
lastname lastname lastname lastname
that that this this time time defines defines aa column column to to all all columns columns in in the the author author table. table. Perform Perform now now the the statement: statement: that this time defines a column to all columns in the author table. Perform now the statement: that this time defines a column to all columns in the author table. Perform now the that this time defines a column to all columns in the author table. Perform now the statement: statement: INTO INTO INTO INTO
VALUES VALUES VALUES VALUES
(1000, (1000, (1000, (1000,
'Knud', 'Knud', 'Knud', 'Knud',
'Larsen'); 'Larsen'); 'Larsen'); 'Larsen');
and and you you will will see see that that both both the the view view and and the the original original table table is is updated. updated. This This means means that that an an update of the view also updates the parent table, but there are the following conditions: and you will see that both the view and the original table is updated. This means that and you will see that both the view and thetable, original table updated. This means that an an update thesee view updates the and parent buttable thereisisare the following conditions: and you of will thatalso both the view the original updated. This means that an update of of the the view view also also updates updates the the parent parent table, table, but but there there are are the the following following conditions: conditions: update update of the view also updates the parent table, but there are the following conditions: -- the the SELECT SELECT statement statement may may not not use use DISTINCT DISTINCT -- the contain functions SELECT statement may not use DISTINCT the SELECT statement may not use DISTINCT contain functions -- the SELECT statement may not use DISTINCT operators -- the SELECT statement may not contain the SELECT statement may not contain functions functions operators -- the SELECT statement may not contain functions -- the SELECT statement may not use ORDER BY contain operators the SELECT statement may not contain operators use ORDER BY -- the SELECT statement may not contain operators SELECT statement can only one table -- the may not use ORDER BY may only not use ORDER BY the SELECT SELECT statement statement may can one tableBY -- the not use ORDER SELECT statement’s WHERE part may not -- the SELECT statement can only use one table SELECT statement’s statement can only use one table the SELECT SELECT WHERE partone may not use use aa SELECT SELECT statement statement (se (se below) below) -- the statement can only use table -- the SELECT statement may not use GROUP BY or HAVING SELECT statement’s WHERE part may not use a SELECT statement (se SELECT statement’s WHERE partGROUP may not BY use or a SELECT statement (se below) below) theSELECT SELECTstatement’s statement WHERE may not part use HAVING -- the may not use a SELECT statement (se below) -- the SELECT statement must include all columns from the parent table SELECT statement may not use use GROUP GROUP BY or or HAVING HAVING the SELECT statement may not BY SELECTstatement statementmay must all columns the parent table that that is is -- the SELECT notinclude use GROUP BY orfrom HAVING defined NOT NULL -- the SELECT statement must include all columns from the parent table that the SELECT statement must include all columns from the parent table that is is defined NOTstatement NULL must -- the SELECT include all columns from the parent table that is defined NOT NULL defined NOT NULL defined NOT NULL
Download free eBooks at bookboon.com 180 180 180
JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS
Final FInal examples examples
INNER SELECT STATEMENTS
It is possible to use an inner SELECT statement in a WHERE clause where an inner SELECT returns data that is used in the condition. An inner SELECT can be used both in a SELECT, INSERT, UPDATE and DELETE – typically associated with operators. A typical example is, using SELECT IN: SELECT isbn, title FROM book WHERE pubnr IN (SELECT pubnr FROM publisher WHERE name = 'Prentice Hall' OR name = 'Addison Wesley');
The result is isbn and title of all books published by either Prentice Hall or Addison Wesley. The result is isbn and title of all books published by either Prentice Hall or Addison Wesley. Of course one can achieve the same otherwise, but SELECT IN is easy to understand. Of course one can achieve the same otherwise, but SELECT IN is easy to understand. NY026057B
TMP PRODUCTION 6x4
4
12/13/2013
ACCCTR00
PSTANKIE
gl/rv/rv/baf
Bookboon Ad Creative
All rights reserved.
© 2013 Accenture.
Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon
Download free eBooks at bookboon.com 181 181
Click on the ad to read more
JAVA JAVA6:6:JDBC JDBCAND ANDDATABASE DATABASEAPPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Final FInalexamples examples FInal examples
As Asanother anotherexample, example,creates createsthe thefollowing followingscript scripta anew newtable tablewith withallallthe themath mathbooks bookswhen when As another example, creates the following script a new table with all the math books when the thetable tablemust mustcontain containthe thesame samecolumns columnsasastable tablebook, book,but butexcept exceptcolumn columncatnr: catnr: the table must contain the same columns as table book, but except column catnr: use books; use books; create table math ( create table math ( isbn char(13) not null, isbn char(13) not null, title varchar(100) not null, title varchar(100) not null, edition int, edition int, year char(4), year char(4), pages int, pages int, pubnr int not null, pubnr int not null, primary key (isbn), primary key (isbn), foreign key (pubnr) references publisher (pubnr)); foreign key (pubnr) references publisher (pubnr)); INSERT INSERT SELECT SELECT
INTO math (isbn, title, edition, year, pages, INTO math (isbn, title, edition, year, pages, isbn, title, edition, year, pages, pubnr FROM isbn, title, edition, year, pages, pubnr FROM
pubnr) pubnr) book WHERE catnr = 2; book WHERE catnr = 2;
Whatisisinteresting interesting is thelast last INSERTINTO INTO statementthat that insertsdata data froma aSELECT. SELECT. What What is interestingisisthe the lastINSERT INSERT INTOstatement statement thatinserts inserts datafrom from a SELECT. STOREDPROCEDURES PROCEDURES STORED STORED PROCEDURES
willconclude conclude thisappendix appendix witha avery very briefintroduction introduction to storedprocedures, procedures, whichisis I IIwill will concludethis this appendixwith with a verybrief brief introductiontotostored stored procedures,which which is actually a large area. A stored procedure is a routine consisting of SQL statements thatare are actually actuallya alarge largearea. area.AAstored storedprocedure procedureisisa aroutine routineconsisting consistingofofSQL SQLstatements statementsthat that are storedon on thedatabase database servertogether together withthe the databasetables, tables, andthe the ideaisisofofcourse course stored stored onthe the databaseserver server togetherwith with thedatabase database tables,and and theidea idea is of course savethe the SQLprocedures procedures whichare are oftenneeded, needed, butalso also thata astored stored procedureisis toto tosave save theSQL SQL procedureswhich which areoften often needed,but but alsothat that a storedprocedure procedure is translatedinto intoananinternal internalformat formatand andthus thusisiseffective. effective. translated translated into an internal format and thus is effective. BelowI Iwill will showa afew few examplesofofsimple simple procedures,and and howthey they arecreated created using Below Below I willshow show a fewexamples examples of simpleprocedures, procedures, andhow how theyare are createdusing using MySQL Workbench. In the database right-click on Stored Procdures and select Create Stored MySQL MySQLWorkbench. Workbench.InInthe thedatabase databaseright-click right-clickon onStored StoredProcdures Procduresand andselect selectCreate CreateStored Stored Procedure and MySQL Workbench creates a skeleton: Procedure and MySQL Workbench creates a skeleton: Procedure and MySQL Workbench creates a skeleton: CREATE PROCEDURE 'new_procedure' () CREATE PROCEDURE 'new_procedure' () BEGIN BEGIN END END
You Youcan canthen thenwrite writea astored storedprocedure procedurenamed namedHello Helloasasfollows: follows: You can then write a stored procedure named Hello as follows: CREATE PROCEDURE Hello () CREATE PROCEDURE Hello () BEGIN BEGIN SELECT 'Hello World'; SELECT 'Hello World'; END END
Download free eBooks at bookboon.com 182 182 182
JAVA 6: JDBC AND DATABASE APPLICATIONS JAVA JAVA 6: 6: JDBC JDBC AND AND DATABASE DATABASE APPLICATIONS APPLICATIONS JAVA 6: JDBC AND DATABASE APPLICATIONS
Final examples FInal FInal examples examples FInal examples
and ifif you then click Apply the procedure isis translated, and ifif there isis no errors, itit isis stored and you then click Apply the procedure translated, and there no errors, stored and if you then click Apply the procedure is translated, and if there is no errors, it is stored and if you then click Apply the procedure is translated, and if there is no errors, it is stored inin the database and MySQL Workbench will show the finished code: in the the database database and and MySQL MySQL Workbench Workbench will will show show the the finished finished code: code: in the database and MySQL Workbench will show the finished code: USE USE 'books'; 'books'; USE 'books'; DROP DROP procedure procedure IF IF EXISTS EXISTS 'Hello'; 'Hello'; DROP procedure IF EXISTS 'Hello'; DELIMITER $$ $$ DELIMITER DELIMITER $$ USE 'books'$$ USE 'books'$$ USE 'books'$$ CREATE PROCEDURE PROCEDURE Hello Hello () () CREATE CREATE PROCEDURE Hello () BEGIN BEGIN BEGIN SELECT 'Hello 'Hello World'; World'; SELECT SELECT 'Hello World'; END$$ END$$ END$$ DELIMITER DELIMITER ; ; DELIMITER ;
The firstthing thingthat thathappens happensisis thatthe theprocedure procedureisis deletedifif thereisis alreadya aaprocedure procedure The first that deleted there already The The first first thing thing that that happens happens is is that that the the procedure procedure is is deleted deleted if if there there is is already already a procedure procedure withthe thesame samename. name.Next, Next,define definea aapunctuation punctuationused usedtoto tomark marktoto toMySQL MySQLthat thatthe theprocedure procedure with with the same name. Next, define punctuation used mark MySQL that the procedure with the same name. Next, define a punctuation used to mark to MySQL that the procedure ends. Bydefault defaultitit dollarsign. sign.After Afterthe theprocedure procedureisis translatedand andsaved, saved,itit canbebe ends. By isisa aadollar translated can ends. ends. By By default default it it is is a dollar dollar sign. sign. After After the the procedure procedure is is translated translated and and saved, saved, it it can can be be performed as follows: performed as follows: performed as follows: performed as follows: CALL CALL Hello; Hello; CALL Hello;
and the result isthat thatthe theprocedure procedureprints printsHello HelloWorld Worldon onthe thescreen. screen. and the result and andthe theresult resultisis is that that the the procedure procedure prints prints Hello Hello World World on on the the screen. screen. isobviously obviouslynot nota aaparticularly particularlyinteresting interestingprocedure, procedure,but butitit shows the principle and that It shows the principle and that ItIt Itisis is obviously obviously not not a particularly particularly interesting interesting procedure, procedure, but but it itshows showsthe theprinciple principleand andthat that is simply the case that one or more SQL statements can be executed under a common simply the case that one or more SQL statements can be executed under a common isis simply the case that one or more SQL statements can be executed under a common is simply the case that one or more SQL statements can be executed under a common name. Inaddition additiontoto seeing some more examples, there are basically two things that must name. seeing some more examples, there are basically two things that must name. name.InIn In addition addition to toseeing seeingsome somemore moreexamples, examples,there thereare arebasically basicallytwo twothings thingsthat thatmust must be addressed, namely parameters and program logic. be addressed, namely parameters and program logic. bebeaddressed, addressed,namely namelyparameters parametersand andprogram programlogic. logic. As anexample exampleisis below shown a procedure, that calculate the number og books, where the As below shown procedure, that calculate the number og books, where the As Asanan an example example is isbelow belowshown showna aaprocedure, procedure,that thatcalculate calculatethe thenumber numberog ogbooks, books,where wherethe the number of pages is greater than or equal to a and less than or equal to b, and where a and number of pages is greater than or equal to a and less than or equal to b, and where a and number of pages is greater than or equal to a and less than or equal to b, and where a and number of pages is greater than or equal to a and less than or equal to b, and where a and b areinput inputparameters. parameters.The Theresult resultisis is saved savedinin in anoutput outputparameter parameterc:c: c: b are bbare are input input parameters. parameters. The The result result issaved saved inanan an output output parameter parameter c: CREATE CREATE PROCEDURE PROCEDURE 'counter' 'counter' (IN (IN a a int, int, CREATE PROCEDURE 'counter' (IN a int, BEGIN BEGIN BEGIN SELECT SELECT count(isbn) count(isbn) FROM FROM book book WHERE WHERE a a SELECT count(isbn) FROM book WHERE a END END END
IN IN b b int, int, OUT OUT c c int) int) IN b int, OUT c int)