Execute the following SQL script inside MySQL Workbench:create database SampleDB; use SampleDB; CREATE TABLE `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(45) NOT NULL, `password` varchar(45) NOT NULL, `fullname` varchar(45) NOT NULL, `email` varchar(45) NOT NULL, PRIMARY KEY (`user_id`) );Or if you are using MySQL Command Line Client program, save the above script into a file, let’s say, SQLScript.sqland execute the following command:
source Path\To\The\Script\File\SQLScript.sql
Here’s an example screenshot taken while executing the above script in MySQL Command Line Client program:
A prepared statement is one that contains placeholders (in form question marks ?) for dynamic values will be set at runtime. For example:
SELECT * from Users WHERE user_id=?
Here the value of user_id is parameterized by a question mark and will be set by one of the setXXX() methods from the PreparedStatement interface, e.g. setInt(int index, int value).
String dbURL = "jdbc:mysql://localhost:3306/sampledb";
String username = "root";
String password = "secret";
try {
Connection conn = DriverManager.getConnection(dbURL, username, password);
if (conn != null) {
System.out.println("Connected");
}
} catch (SQLException ex) {
ex.printStackTrace();
}Once the connection was established, we have a Connection object which can be used to create statements in order to execute SQL queries. In the above code, we have to close the connection explicitly after finish working with the database:conn.close();However, since Java 7, we can take advantage of the try-with-resources statement which will close the connection automatically, as shown in the following code snippet:
try (Connection conn = DriverManager.getConnection(dbURL, username, password)) {
// code to execute SQL queries goes here...
} catch (SQLException ex) {
ex.printStackTrace();
}If you are using Java 7 or later, this approach is recommended. The sample programs in this tutorial are all using this try-with-resources statement to make a database connection.NOTE: For details about connecting to a MySQL database, see the article: Connect to MySQL database via JDBC. String sql = "INSERT INTO Users (username, password, fullname, email) VALUES (?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "bill");
statement.setString(2, "secretpass");
statement.setString(3, "Bill Gates");
statement.setString(4, "bill.gates@microsoft.com");
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}In this code, we create a parameterized SQL INSERT statement and create a PreparedStatement from the Connection object. To set values for the parameters in the INSERT statement, we use the PreparedStatement‘s setString() methods because all these columns in the table Users are of type VARCHAR which is translated to String type in Java. Note that the parameter index is 1-based (unlike 0-based index in Java array).The PreparedStatement interface provides various setXXX() methods corresponding to each data type, for example:String sql = "SELECT * FROM Users";
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery(sql);
int count = 0;
while (result.next()){
String name = result.getString(2);
String pass = result.getString(3);
String fullname = result.getString("fullname");
String email = result.getString("email");
String output = "User #%d: %s - %s - %s - %s";
System.out.println(String.format(output, ++count, name, pass, fullname, email));
}Output:User #1: bill - secretpass - Bill Gates - bill.gates@microsoft.com
Because the SQL SELECT query here is static so we just create a Statement object from the connection. The while loop iterates over the rows contained in the result set by repeatedly checking return value of the ResultSet’s next() method. The next() method moves a cursor forward in the result set to check if there is any remaining record. For each iteration, the result set contains data for the current row, and we use the ResultSet’s getXXX(column index/column name) method to retrieve value of a specific column in the current row, for example this statement:String name = result.getString(2);Retrieves value of the second column in the current row, which is the username field. The value is casted to a String because we know that the username field is of type VARCHAR based on the database schema mentioned previously. Keep in mind that the column index here is 1-based, the first column will be at index 1, the second at index 2, and so on. If you are not sure or don’t know exactly the index of column, so passing a column name would be useful:
String fullname = result.getString("fullname");For other data types, the ResultSet provide appropriate getter methods:String sql = "UPDATE Users SET password=?, fullname=?, email=? WHERE username=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "123456789");
statement.setString(2, "William Henry Bill Gates");
statement.setString(3, "bill.gates@microsoft.com");
statement.setString(4, "bill");
int rowsUpdated = statement.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("An existing user was updated successfully!");
}This code looks very similar to the INSERT code above, except the query type is UPDATE.String sql = "DELETE FROM Users WHERE username=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "bill");
int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println("A user was deleted successfully!");
}So far we have one through some examples demonstrating how to use JDBC API to execute SQL INSERT, SELECT, UPDATE and DELETE statements. The key points to remember are:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.