Java Database Step by Step
Java Database Step by Step
Java Database Step by Step
2. Setting-up MySQL
Assume that the MySQL server is running on the default TCP port number 3306.
On MySQL, instead of using the "mysql" command-line client program provided, you can write your
own client programs (in Java or other languages) to access the MySQL server. Your client programs
shall connect to the database server at the given IP address and TCP port number, issue the SQL
commands, and process the results received.
Biruk A.
3. Open the unzipped folder. Look for the JAR file " mysql-connector-java-8.0.
{xx}.jar".
The Absolute Full-path Filename for this JAR file is "C:\myWebProject\mysql-
connector-java-8.0.{xx}\mysql-connector-java-8.0.{xx}.jar". Take note of
this super-long filename that you will need later. COPY and SAVE in a scratch pad so
that you can retrieve later.
For macOS
1. Download the latest MySQL JDBC driver from http://dev.mysql.com/downloads ⇒
MySQL Connectors ⇒ Connector/J ⇒ Connector/J 8.0.{xx}, where {xx} is the latest
update number ⇒ In "Select Operating System", choose "Platform Independent" ⇒
Compressed TAR Archive (e.g., mysql-connector-java-8.0.{xx}.tar.gz.
2. Double-click on the downloaded TAR file to expand into folder "mysql-connector-
java-8.0.{xx}".
3. Move the expanded folder into your project directory " ~/myWebProject".
4. Open the expanded folder. Look for the JAR file " mysql-connector-java-8.0.
{xx}.jar".
The Absolute Full-path Filename for this JAR file is "~/myWebProject/mysql-
connector-java-8.0.{xx}/mysql-connector-java-8.0.{xx}.jar". Take note of
this super-long filename that you will need later. COPY and SAVE in a scratch pad so
that you can retrieve later.
(For Advanced User Only)
You can compile Java database programs without the JDBC driver. But to run the JDBC programs, the
JDBC driver's JAR-file must be included in the environment variable CLASSPATH, or in the java's
command-line option -cp.
You can set the -cp option for Java runtime as follows:
// For windows
Prior to JDK 9, you can copy the JAR file into JDK's extension directory at " <JAVA_HOME>\jre\lib\
ext" (Windows) or "/Library/Java/Extensions" (macOS). JDK 9 removes this extension mechanism.
2.4 Setup Database
We have to set up a database before embarking on our database programming. We shall call our
database "ebookshop" which contains a table called "books", with 5 columns, as below:
Database: ebookshop
Table: books
Biruk A.
+-------+----------------------------+---------------+---------+-------+
+-------+----------------------------+---------------+---------+-------+
+-------+----------------------------+---------------+---------+-------+
Start MySQL Server : Start the MySQL server and verify the server's TCP port number from the
console messages. I shall assume that MySQL server is running on the default port number of 3306.
c:
cd \myWebProject\mysql\bin
mysqld --console
// For macOS
Start a MySQL client : I shall also assume that there is an authorized user called " myuser" with
password "xxxx".
c:
cd \myWebProject\mysql\bin
mysql -u myuser -p
cd /usr/local/mysql/bin
./mysql -u myuser -p
Biruk A.
Run the following SQL statements to create our test database and table.
use ebookshop;
id int,
title varchar(50),
author varchar(50),
price float,
qty int,
insert into books values (1001, 'Java for dummies', 'Tan Ah Teck', 11.11, 11);
insert into books values (1002, 'More Java for dummies', 'Tan Ah Teck', 22.22, 22);
insert into books values (1003, 'More Java for more dummies', 'Mohammad Ali', 33.33,
33);
insert into books values (1004, 'A Cup of Java', 'Kumar', 44.44, 44);
insert into books values (1005, 'A Teaspoon of Java', 'Kevin Jones', 55.55, 55);
Biruk A.
We shall illustrate Java Database programming by the following examples.
Biruk A.
2
2
3
2
4
2
5
2
6
2
String title = rset.getString("title");
7
double price = rset.getDouble("price");
2
int qty = rset.getInt("qty");
8
System.out.println(title + ", " + price + ", " + qty);
2
++rowCount;
9
}
3
System.out.println("Total number of records = " + rowCount);
0
3
} catch(SQLException ex) {
1
ex.printStackTrace();
3
} // Step 5: Close conn and stmt - Done automatically by try-with-resources
2
(JDK 7)
3
}
3
}
3
4
3
5
3
6
3
7
3
8
c:
cd \myWebProject
javac JdbcSelectTest.java
Biruk A.
// macOS: The Java source directory is "~/myWebProject"
cd ~/myWebProject
javac JdbcSelectTest.java
Run : It is rather difficult to run the program, as you need to include the MySQL JDBC Driver in
the classpath (via -cp option) as follows:
// For windows
c:
cd \myWebProject
// For macOS
cd ~/myWebProject
You should COPY and SAVE this command to a scratch pad, so that you don't need to type this
super-long command again and again.
The -cp includes two paths separated by a " ;" (Windows) or ":" (macOS). The "." denotes the
current directory (to locate the JdbcSelectTest) followed by the full-path filename of the MySQL
JDBC Driver JAR-file (that I asked you to take note earlier).
Biruk A.
3.In Line 7, we allocate a Connection object (called conn) via
DriverManager.getConnection(database-url, db-user, password). The Java program
uses a so-called database-URL to connect to the server:
o For MySQL:
o // Syntax
o // Example
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/ebookshop",
"myuser", "xxxx");
Exercises: Modify your Java program to issue the following SELECT statements and display all the
columns retrieved. Make sure you modify the ResultSet processing to process only the columns
retrieved (otherwise, you will get a "Column not found" error).
Biruk A.
1. SELECT * FROM books
2. SELECT title, author, price, qty FROM books WHERE author = 'Tan Ah Teck' OR
price >= 30 ORDER BY price DESC, id ASC
Biruk A.
2
0
2
1
2
2
2
3
2
4
2
5
2 while(rset.next()) { // Move the cursor to the next row
6 System.out.println(rset.getInt("id") + ", "
2 + rset.getString("author") + ", "
7 + rset.getString("title") + ", "
2 + rset.getDouble("price") + ", "
8 + rset.getInt("qty"));
2 }
9 } catch(SQLException ex) {
3 ex.printStackTrace();
0 } // Step 5: Close conn and stmt - Done automatically by try-with-resources
3 }
1}
3
2
3
3
3
4
3
5
3
6
3
7
See the previous example on how to compile and run this program! Point to this Java file
"JdbcUpdateTest"!
Exercises: Modify your Java program to issue the following SQL statements:
Biruk A.
1.Increase the price by 50% for "A Cup of Java".
2.Set the qty to 0 for "A Teaspoon of Java".
Biruk A.
1
2 // INSERT multiple records
2 sqlInsert = "insert into books values "
2 + "(3002, 'Gone Fishing 2', 'Kumar', 22.22, 22),"
3 + "(3003, 'Gone Fishing 3', 'Kumar', 33.33, 33)";
2 System.out.println("The SQL statement is: " + sqlInsert + "\n"); // Echo
4for debugging
2 countInserted = stmt.executeUpdate(sqlInsert);
5 System.out.println(countInserted + " records inserted.\n");
2
6 // INSERT a partial record
2 sqlInsert = "insert into books (id, title, author) values (3004, 'Fishing
7101', 'Kumar')";
2 System.out.println("The SQL statement is: " + sqlInsert + "\n"); // Echo
8for debugging
2 countInserted = stmt.executeUpdate(sqlInsert);
9 System.out.println(countInserted + " records inserted.\n");
3
0 // Issue a SELECT to check the changes
3 String strSelect = "select * from books";
1 System.out.println("The SQL statement is: " + strSelect + "\n"); // Echo
3For debugging
2 ResultSet rset = stmt.executeQuery(strSelect);
3 while(rset.next()) { // Move the cursor to the next row
3 System.out.println(rset.getInt("id") + ", "
3 + rset.getString("author") + ", "
4 + rset.getString("title") + ", "
3 + rset.getDouble("price") + ", "
5 + rset.getInt("qty"));
3 }
6 } catch(SQLException ex) {
3 ex.printStackTrace();
7 } // Step 5: Close conn and stmt - Done automatically by try-with-resources
3 }
8}
3
9
4
0
4
Biruk A.
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
See the previous example on how to compile and run this program! Point to this Java file
"JdbcInsertTest"!
Notes:
Biruk A.
1.You cannot insert two records with the same primary key (i.e., id) value. Hence, we issue a
DELETE before INSERT new record. In this way, you can re-run the program.
2.If you insert a partial record, the missing columns will be set to their default values.
Exercise: Modify your Java program to issue the following SQL statements:
1.Delete all books with id > 8000; and insert: (8001, 'Java ABC', 'Kevin Jones', 15.55, 55) and
(8002, 'Java XYZ', 'Kevin Jones', 25.55, 55);
4. JDBC Cycle
ERROR MESSAGE:
(macOS/Linux) NullPointerException
PROBABLE CAUSES: MySQL JDBC Driver Connector/J was NOT (properly) installed.
POSSIBLE SOLUTION:
1. Read "2.3 Install MySQL JDBC Driver" again, again and again...
2. You need to include MySQL JDBC driver via "cp" option to run your JDBC program:
3. For Tomcat, you may copy the driver JAR-file into Tomcat's "lib" directory.
Biruk A.
PROBABLE CAUSES:
2. The program was connecting to a wrong TCP port number or wrong hostname (or IP
address)
POSSIBLE SOLUTION:
1. Make sure that server has been started. Note down the server's port number
3. Run a MySQL client, issue command "status" to confirm the server's TCP port
number.
4. Run a mysql client, use "mysql -u root -p --port=xxxx" to specify the port
number to
POSSIBLE SOLUTION:
1. Check you userid and password by logging in thru mysql command-line client
jdbc:mysql://localhost:3306/ebookshop?
allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC
Biruk A.
SYMPTOM: Can compile the JDBC program but Runtime Error
POSSIBLE SOLUTION:
jdbc:mysql://localhost:3306/ebookshop?
allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC
POSSIBLE SOLUTION: Create the database using a client, before running the Java
program.
POSSIBLE SOLUTION: Check your SQL statement and the database tables.
POSSIBLE SOLUTION: Make sure that the column 'xxx' is included in the SELECT
statement,
Biruk A.
so that it is included in the ResultSet.
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near .... at line x
Biruk A.