December 21, 2014
Hot Topics:

JDBC and MySQL: Discussion and Sample Code for JDBC Programs, Page 3

  • October 5, 2004
  • By Richard G. Baldwin
  • Send Email »
  • More Articles »

Discussion and Sample Code for JDBC Programs

With all of the above as preparation, it is now time to learn how to write JDBC programs to administer and manipulate the data on the MySQL database server.

Three separate programs

I will explain three programs. The first program, named Jdbc11 shows how to:

  • Log onto the server as the administrator named root.
  • Create a new database named JunkDB.
  • Register a new user named auser on the database named JunkDB with six different privileges and a password of drowssap.

The second program named Jdbc12 shows how to:

  • Log onto the server as the administrator named root.
  • Revoke the privileges of and remove the user named auser.
  • Delete the database named JunkDB.

The third program named Jdbc10 shows how to log onto the server as the user named auser and to manipulate the database named JunkDB in a variety of ways.

I will break each of these programs down into fragments and discuss the fragments. Complete listings of all the programs are shown in Listings 40, 41, and 42 near the end of the lesson.

Jdbc11 - Create a database and make a new user

The purpose of the program named Jdbc11 is to log onto the master database named mysql as the default administrator named root whose password is blank in order to perform the following updates on the MySQL database server:

  • Create a new database named JunkDB.
  • Create a new user named auser with a password of drowssap with six different privileges on the database named JunkDB.

The output, or lack thereof

These two operations produce no visible output when successful. However, they produce error messages in the output when unsuccessful.

(Note, however, that print statements in the program produce several lines of output that are independent of the operations being performed on the database server.)

Server must be running

The MySQL server must be running on localhost before this program is started. Instructions for starting and stopping the database server were provided earlier (see Listing 1, Figure 1, Listing 2, and Figure 2).

The program was tested using Java SDK 1.4.2 under WinXP, MySQL version 4.0.21-win, and JDBC connector version mysql-connector-java-3.0.15-ga.

Critical steps in using JDBC

There are five critical steps in using JDBC to manipulate a database:

  1. Load and register the JDBC driver classes (programming interface) for the database server that you intend to use.
  2. Get a Connection object that represents a connection to the database server (analogous to logging onto the server).
  3. Get one or more Statement objects for use in manipulating the database.
  4. Use the Statement objects to manipulate the database.
  5. Close the connection to the database.

I will highlight these five steps in the discussion of the sample program that follows.

Beginning of class definition for Jdbc11

The first program fragment for the program named Jdbc11 is shown in Listing 3. The entire program is shown in Listing 40 near the end of the lesson.

public class Jdbc11 {
public static void main(String args[]){
System.out.println(
"Copyright 2004, R.G.Baldwin");
try {
Statement stmt;

Listing 3

The code in Listing 3 is straightforward, showing the beginning of the class, the beginning of the main method, and a print statement.

Listing 3 also declares a local variable of type Statement. I will have more to say about the Statement interface later.

Register the JDBC driver for MySQL

Listing 4 shows the statement that implements the first critical step listed earlier (load and register the JDBC driver classes). This statement registers the MySQL driver classes with the Java program, making it possible for this program to manipulate data on the MySQL server.

 Class.forName("com.mysql.jdbc.Driver");

Listing 4

Reference to the driver class

The following statement appears in the MySQL Connector documentation, Section 2.2.1.entitled Setting the CLASSPATH (For Standalone Use).

"If you are going to use the driver with the JDBC DriverManager, you would use "com.mysql.jdbc.Driver" as the class that implements java.sql.Driver."

This information is also provided in the connector documentation in Section 2.2.2.entitled Driver Class Name and JDBC URL Format.

The Driver interface

Note the reference to the Driver interface in the above quotation. Here is some of what Sun has to say about the Driver interface:

"The interface that every driver class must implement.

The Java SQL framework allows for multiple database drivers.

Each driver should supply a class that implements the Driver interface.

The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to connect to the target URL. ...

When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a driver by calling

Class.forName("foo.bah.Driver")"

The name of the driver class

In order to use a JDBC program with a specific database server, you must obtain the name of this critical driver class from the database vendor (or from some third party that supports the database server). You must then cause your program to load the class.

This is the class that connects the other classes in the connector package to the Java program. Without it, the Java program would be unable to communicate successfully with the database server.

Loading the driver class

The statement in Listing 4 causes this class to be loaded as described in the Sun documentation quoted above.

(If you are unfamiliar with the use of the forName method of the class named Class, see The Essence of OOP using Java: Static Members for a brief introduction to the class named Class. Then open your Google search engine, set the number of results to 100, and search for all of the keywords java forname richard baldwin. This should point you to several previous lessons that I have published that discuss this topic. If you don't find what you need there, click on the link on the bottom of the last Google page that reads repeat the search with the omitted results included to see even more lessons.)

Specification of Driver class as a String

There are several alternative ways to register the Driver class, only one of which is shown in Listing 4. The statement in Listing 4 makes it possible to specify the Driver class as a String. The primary advantage of this approach is that this string can be obtained by the program in a variety of ways at runtime.

Although the string was hard coded into this simple program, that is not a requirement. For a more general program intended to be used with two or more database servers, this string would most likely be provided as some form of user input.

The URL of the database server

MySQL and other similar database engines behave as servers on a network. They are identified by a URL much as other types of servers (such as HTTP servers and FTP servers) are identified. The next fragment defines the URL for the MySQL database server that I used in this sample program.

The code in Listing 5 defines the URL of the master database named mysql on the MySQL database server residing on localhost and servicing the default port number 3306.

(I could have omitted the default port number from the URL, but I decided to include it to remind me to mention it. Note that the "//" characters shown to the right of "mysql:" form part of the URL. They are not comment indicators.)

 String url =
"jdbc:mysql://localhost:3306/mysql";

Listing 5

The URL format is provided in the connector documentation in Section 2.2.2.entitled Driver Class Name and JDBC URL Format. The URL format contains several optional elements. This URL will be referenced in the statement in Listing 6 for the purpose of getting a connection to the database.

Get a connection to the database

The code in Listing 6 implements the second critical step listed earlier (get a connection object).

Listing 6 gets a connection to the database at the specified URL (mysql on localhost port 3306) for a user named root with a blank password. As you are already aware, this user is the default administrator having full privileges to do anything, including creating new databases and registering new users on those databases.

 Connection con =
DriverManager.getConnection(
url,"root", "");

Listing 6

In effect, Listing 6 logs the JDBC program onto the MySQL database server in a manner that is analogous to the first line in Figures 3, 4, and 5 as well as the statements in the batch files shown in Listings 32, 34, 36, and 38.

The getConnection method

The getConnection method is a static method of the DriverManager class. When getConnection is invoked, the DriverManager will attempt to locate a suitable driver from among those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.

There are several overloaded versions of the getConnection method. The version used in Listing 6 attempts to establish a connection to the given database URL for a specific user with a specific password.

If the attempt to get a connection to the database server is successful, the method returns an object of type Connection. In this program, a reference to the Connection object is stored in the reference variable named con.

If the attempt is not successful, an exception of type SQLException will be thrown. Information pertinent to the nature of the problem will be encapsulated in the SQLException object.

As you will see later, SQL statements are executed and results are returned within the context of a connection.

Display some information

The code in Listing 7 is not critical to the program. This code simply displays information about the URL and the connection.

 System.out.println("URL: " + url);
System.out.println("Connection: " + con);

Listing 7

Get a Statement object

The code in Listing 8 implements the third critical step listed earlier (get one or more Statement objects).

This code invokes the createStatement method of the Connection interface to get an object of type Statement.

 stmt = con.createStatement();

Listing 8

Recall that con is a reference to an object of type Connection. A Connection object defines a connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

According to Sun, a Statement object is:

"... used for executing a static SQL statement and returning the results it produces."

The results that are returned

The results, if any, are returned in the form of a ResultSet object. I will have more to say about the ResultSet interface later in conjunction with the discussion of the program named Jdbc10.

(The SQL commands used in this program don't return any results.)

Methods of the Statement interface

The Statement interface declares many methods that can be used to access the database server and to manipulate the data in the database. One of those methods is executeUpdate, which will be used in this program.

The executeUpdate method has a single String parameter. This parameter must be a valid SQL command. The method is used to execute SQL INSERT, UPDATE or DELETE statements. In addition, other SQL statements that return nothing can be executed using this method.

Create the new database

The code in Listing 9 implements the fourth critical step in the list provided earlier, (use of a Statement object to manipulate the database).

Listing 9 invokes the executeUpdate method on the Statement object to create the new database named JunkDB.

 stmt.executeUpdate(
"CREATE DATABASE JunkDB");

Listing 9

The executeUpdate method

Sun has this to say about the executeUpdate method:

"public int executeUpdate(Stringsql) throws SQLException

Executes the given SQL statement, ...

Parameters: sql - an SQL INSERT, UPDATE or DELETE statement or an SQL statement that returns nothing

Returns: either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing."

The method parameter is an SQL command

Note the similarity of the method parameter in Listing 9 to the interactive input shown in Figure 4 and the contents of the text file shown in Listing 33.

In all three cases, an SQL command is invoked on the database server to cause a new database named JunkDB to be created. This SQL command returns nothing, so it is suitable for use with the executeUpdate method described above.

In all three cases, the SQL command is invoked by the default administrator named root who has the ability to create new databases.

Make a new user

The code in Listing 10 also implements the fourth critical step listed earlier, (use of a Statement object to manipulate the database).

The code in Listing 10 invokes the executeUpdate method once again to make a new user named auser who is capable of accessing the database named JunkDB from localhost using the password drowssap with six different privileges.

 stmt.executeUpdate(
"GRANT SELECT,INSERT,UPDATE,DELETE," +
"CREATE,DROP " +
"ON JunkDB.* TO 'auser'@'localhost' " +
"IDENTIFIED BY 'drowssap';");
Listing 10

Another SQL command

Once again, note the similarity of the executeUpdate method parameter in Listing 10 to the interactive input shown in Figure 5 and to the contents of the text file shown in Listing 35.

Figure 5, Listing 10, and Listing 35 illustrate three different ways for the default administrator named root to invoke the same SQL command on the database server.

Close the connection and terminate the program

Listing 11 implements the fifth critical step listed earlier, closing the connection and terminating the program.

 con.close();
}catch( Exception e ) {
e.printStackTrace();
}//end catch
}//end main
}//end class Jdbc11

Listing 11

The results of running the program named Jdbc11

Once this program has been run successfully, the MySQL database server contains a database named JunkDB, as well as a user named auser, having various privileges relative to that database with a password of drowssap.

At this point, it is possible to execute JDBC programs by which the user named auser manipulates the contents of the database named JunkDB. That will be the purpose of the program named Jdbc10, which I will explain later.

First, however, I am going to show you how to write a JDBC program to remove the user named auser and to delete the database named JunkDB from the MySQL database server.

JDBC12 - Remove a user and delete a database

The purpose of the program named Jdbc12 is to log onto the master database named mysql as the default administrator named root whose password is blank in order to perform the following updates on the MySQL database server:

  • Revoke the privileges of and remove a user named auser.
  • Delete a database named JunkDB.

The output

These two operations produce no visible output when successful. However, they produce error messages in the output when unsuccessful.

(Print statements in the program do produce output that is unrelated to the operations listed above.)

A reversal

This program is the reverse of the program named Jdbc11, discussed earlier, which creates the database named JunkDB and registers the user named auser on that database.

Server must be running

The MySQL server must be running on localhost before this program is started. Instructions for starting and stopping the database server were provided earlier (see Listing 1, Figure 1, Listing 2, and Figure 2).

Testing

This program was tested using Java SDK 1.4.2 under WinXP, MySQL version 4.0.21-win, and JDBC connector version mysql-connector-java-3.0.15-ga.

Beginning of the Jdbc12 class

Listing 12 shows the beginning of the class definition and the beginning of the main method for the program named Jdbc12. A complete listing of the program is provided in Listing 41

The code in Listing 12 is the same as the code discussed earlier for the program named Jdbc11. Therefore, I won't repeat that discussion.

public class Jdbc12 {
public static void main(String args[]){
System.out.println(
"Copyright 2004, R.G.Baldwin");
try {
Statement stmt;

//Register the JDBC driver for MySQL.
Class.forName("com.mysql.jdbc.Driver");

//Define URL of database server for
// database named mysql on the localhost
// with the default port number 3306.
String url =
"jdbc:mysql://localhost:3306/mysql";

//Get a connection to the database for a
// user named root with a blank password.
// This user is the default administrator
// having full privileges to do anything.
Connection con =
DriverManager.getConnection(
url,"root", "");

//Display URL and connection information
System.out.println("URL: " + url);
System.out.println("Connection: " + con);

//Get a Statement object
stmt = con.createStatement();

Listing 12

Revoke privileges and remove user named auser

Listing 13 invokes the executeUpdate method four times in succession to cause the database server to revoke privileges for and to remove the user named auser. The SQL commands required to accomplish this were discussed earlier and illustrated in Listings 36 and 37.

 stmt.executeUpdate(
"REVOKE ALL PRIVILEGES ON *.* " +
"FROM 'auser'@'localhost'");
stmt.executeUpdate(
"REVOKE GRANT OPTION ON *.* " +
"FROM 'auser'@'localhost'");
stmt.executeUpdate(
"DELETE FROM mysql.user WHERE " +
"User='auser' and Host='localhost'");
stmt.executeUpdate("FLUSH PRIVILEGES");

Listing 13

Delete the database named JunkDB

Listing 14 invokes the executeUpdate method to delete the database named JunkDB, using an SQL command discussed earlier and illustrated in Listings 38 and 39.

 stmt.executeUpdate(
"DROP DATABASE JunkDB");

Listing 14

Closing the connection and terminating the program

Listing 15 closes the connection and terminates the program.

 con.close();
}catch( Exception e ) {
e.printStackTrace();
}//end catch
}//end main
}//end class Jdbc12

Listing 15

Jdbc10 - Manipulating the data in the database

The behavior of each of the two previous programs has been in the nature of administering or managing the database server. In particular, those programs added and removed databases and users from the database server.

The user perspective

The purpose of the program named Jdbc10 is to illustrate the ability to use JDBC to access a MySQL database server on localhost and to manipulate the data stored in that database.

Server must be running

The MySQL server must be running on localhost before the program named Jdbc10 is started. Instructions for starting and stopping the MySQL database server were provided earlier (see Listing 1, Figure 1, Listing 2, and Figure 2).

Server must be prepared

In addition, a database named JunkDB must have been created on the server and a user named auser must have been registered on that database with a password of drowssap before this program is started.

The user named auser must have privileges that allow for the creation of tables in the database and the insertion of data into the tables. In addition the user must be allowed to perform SELECT queries on the tables in the database.

Creating the database and adding the user

The database may have been created and the user may have been added in at least three different ways:

  • Performing manual data entry with the monitor program as illustrated in Figures 4 and 5.
  • Using the monitor program coupled with data input derived from a text file as illustrated in Listings 32, 33, 34, and 35.
  • Running the program named Jdbc11 discussed earlier.

Behavior of Jdbc10 program

This program:

  • Logs in as auser with a password of drowssap.
  • Accesses the database named JunkDB.
  • Creates a table named myTable.
  • Puts five rows of data into the table named myTable.
  • Accesses the data in the table named myTable.
  • Displays the data.
  • Deletes the table named myTable.

Two different approaches are used to display the contents of the table. The first approach displays all of the data in the table. The second approach displays only the data in a specific row in the table.

A precaution

As a precaution, before attempting to create the new table, the program attempts to delete a table having the same name. If a table having the same name already exists as residue from a previous run, it is deleted.

If it doesn't already exist when the attempt is made to delete it, an exception is thrown. This exception is caught, displayed, and ignored.

The program output

This program produces the output shown in Figure 6 under normal conditions where the table named myTable does not exist when the program is started (the specifics regarding the Connection object may vary from one run to the next).

Copyright 2004, R.G.Baldwin
URL: jdbc:mysql://localhost:3306/JunkDB
Connection: com.mysql.jdbc.Connection@1430b5c
java.sql.SQLException: Base table or view not
found message from server: "Unknown table
'mytable'"No existing table to delete
Display all results:
test_id= 1 str = One
test_id= 2 str = Two
test_id= 3 str = Three
test_id= 4 str = Four
test_id= 5 str = Five
Display row number 2:
test_id= 2 str = Two
Figure 6

Testing

This program was tested using Java SDK 1.4.2 under WinXP, MySQL version 4.0.21-win, and JDBC connector version mysql-connector-java-3.0.15-ga.

Beginning of the class definition

The class definition begins in Listing 16. A complete listing of the program is shown in Listing 42 near the end of the lesson.

public class Jdbc10 {
public static void main(String args[]){
System.out.println(
"Copyright 2004, R.G.Baldwin");
try {
Statement stmt;
ResultSet rs;

//Register the JDBC driver for MySQL.
Class.forName("com.mysql.jdbc.Driver");

Listing 16

Except for the declaration of a variable of type ResultSet, the code in Listing 16 is the same as the code in the two previous programs. I will have more to say about the ResultSet type later.

Define the database URL

Listing 17 defines the URL of the database server and the database that will be accessed later by this program.

 String url =
"jdbc:mysql://localhost:3306/JunkDB";

Listing 17

Note that the previous two programs accessed the master database named mysql, whereas this program accesses the user database named JunkDB. Otherwise, the code in Listing 17 is the same as in the two previous programs.

Get a connection to the database

Listing 18 gets a connection to the database.

 Connection con =
DriverManager.getConnection(
url,"auser", "drowssap");

Listing 18

Recall that the code in Listing 18 is analogous to a specific user logging onto a specific database using a specific password.

The previous two programs got a connection to the master database named mysql for the default administrator named root whose password was blank.

This program gets a connection to the database named JunkDB for the user named auser whose password is drowssap.

Display some information and get a statement object

As in the previous two programs, Listing 19 displays some information about the URL and the connection, and then gets a Statement object.

 //Display URL and connection information
System.out.println("URL: " + url);
System.out.println("Connection: " + con);

//Get a Statement object
stmt = con.createStatement();

Listing 19

Delete the table named myTable if it exists

A table named myTable may already exist in the database named JunkDB for some reason such as the premature ending of a previous run of this program. If the table already exists, it will not be possible to create a new empty table having that name. A requirement of this program is to create an empty table named myTable in a particular format.

Therefore, as a precaution, before attempting to create the new table, the code in Listing 20 attempts to delete a table named myTable. If a table having that name already exists, it is deleted.

If it doesn't already exist when the attempt is made to delete it, an exception is thrown. This exception is simply caught, displayed, and ignored.

 try{
stmt.executeUpdate("DROP TABLE myTable");
}catch(Exception e){
System.out.print(e);
System.out.println(
"No existing table to delete");
}//end catch

Listing 20

The code in Listing 20 invokes the executeUpdate method, with which you are already familiar. Only the syntax of the SQL command provided as a parameter to the method is new to this program.

Create the new table named myTable

The code in Listing 22 invokes the executeUpdate method to create a new table named myTable. I will refer you to an SQL book for a full understanding of the SQL command that is passed as a parameter to the method.

 stmt.executeUpdate(
"CREATE TABLE myTable(test_id int," +
"test_val char(15) not null)");

Listing 22

Briefly, the new table will have two columns. The first column will be named test_id and will be designed to contain integer data.

The second column will be named test_val and will be designed to contain character data up to 15 characters in length (in Java, we might refer to that as String data, except that there is no limit to the length of a String in Java).

Insert some values into the table

Listing 23 invokes the executeUpdate method to insert one value into each column of the first row in the table.

 stmt.executeUpdate(
"INSERT INTO myTable(test_id, " +
"test_val) VALUES(1,'One')");

Listing 23

 

The integer value 1 is inserted into the column named test_id. The three characters, One, are inserted into the column named test_val.

Insert values into four more rows

Listing 24 invokes the executeUpdate method four more times in succession to insert values into the columns in rows 2 through 5. You should be able to examine the SQL commands and determine the values inserted into the table.

 stmt.executeUpdate(
"INSERT INTO myTable(test_id, " +
"test_val) VALUES(2,'Two')");
stmt.executeUpdate(
"INSERT INTO myTable(test_id, " +
"test_val) VALUES(3,'Three')");
stmt.executeUpdate(
"INSERT INTO myTable(test_id, " +
"test_val) VALUES(4,'Four')");
stmt.executeUpdate(
"INSERT INTO myTable(test_id, " +
"test_val) VALUES(5,'Five')");

Listing 24

 

The table is populated

At this point, the first five rows in the table named myTable have been populated with data. The remaining code in the program will:

  • Access and display all of the data in the table.
  • Display the data in a specific row in the table.
  • Delete the table from the database.

Get another Statement object

The code in Listing 25 gets a different Statement object, initialized as shown by the parameters that are passed to the createStatement method.

 stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);

Listing 25

 

I won't try to explain the meaning of the initialization parameters. Rather, I will let you look them up in the Sun documentation for the ResultSet interface, and then perhaps do further research in an SQL book.

The ResultSet interface provides about ten symbolic constants that can be used as parameters to this method. The values of the parameters exercise control over the behavior of the ResultSet object returned by a subsequent query based on the Statement object.

Query the database

All of the database operations to this point have been based on the use of the executeUpdate method of the Statement interface. Recall that I told you earlier that the executeUpdate method can be used to execute SQL commands that don't return anything.

We have now reached the point where we want to execute an SQL command that does return something. For this, we will invoke the executeQuery method on the Statement object.

What does Sun have to say?

Here is part of what Sun has to say about this method:

"public ResultSet executeQuery(Stringsql) throws SQLException

Executes the given SQL statement, which returns a single ResultSet object.

Parameters: sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement

Returns: a ResultSet object that contains the data produced by the given query; never null"

In other words, this method will execute the SQL command on the database and encapsulate the returned values in an object of type ResultSet.

A ResultSet object

A ResultSet object provides access to an encapsulated table of data. The object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row (similar to an iterator or an enumerator in Java).

Once the results are encapsulated in a ResultSet object, the ResultSet interface provides several methods that can be used to extract the information from the object.

Methods of a ResultSet object

The get methods (such as getString) retrieve column values for the current row. You can retrieve values using either the index number of the column or the name of the column. I have read that using the column index is more efficient but I can't give you a reference on that.

(Columns are numbered beginning with 1, not with 0.)

For the get methods, the JDBC driver attempts to convert the underlying data to the specified Java type and returns a suitable Java value.

The life of a ResultSet object

A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

Perform the query

Listing 26 invokes the executeQuery method to perform the query on the database selecting all columns in all rows, and sorting the results in order by the values in the column named test_id. The results are encapsulated in the ResultSet object referred to by the reference variable named rs.

 rs = stmt.executeQuery("SELECT * " +
"from myTable ORDER BY test_id");

Listing 26

 

Display all of the results in the ResultSet object

Listing 27 uses a while loop to:

  • Iterate on the ResultSet object one row at a time.
  • Invoke the getInt method to get and save the value in the column named test_id for each row.
  • Invoke the getString method to get and save the value in the column named test_val for each row.
  • Display the two values on a new output line on the screen.
 System.out.println("Display all results:");
while(rs.next()){
int theInt= rs.getInt("test_id");
String str = rs.getString("test_val");
System.out.println("\ttest_id= " + theInt
+ "\tstr = " + str);
}//end while loop

Listing 27

 

The output

The output produced by the code in Listing 27 is shown in Figure 7.

Display all results:
test_id= 1 str = One
test_id= 2 str = Two
test_id= 3 str = Three
test_id= 4 str = Four
test_id= 5 str = Five
Figure 7

Display the data in row number 2

The code in Listing 28 invokes the absolute method on the same ResultSet object to get, save, and display the data in the two columns of row number 2.

 System.out.println(
"Display row number 2:");
if( rs.absolute(2) ){
int theInt= rs.getInt("test_id");
String str = rs.getString("test_val");
System.out.println("\ttest_id= " + theInt
+ "\tstr = " + str);
}//end if

Listing 28

 

(Note that row numbers begin with 1 and do not begin with 0 as would be the case in most Java contexts. Although not demonstrated here, the same is true for column numbers. Apparently this is the norm in database work.)

The output

Figure 8 shows the output produced by the code in Listing 28.

Display row number 2:
test_id= 2 str = Two
Figure 8

Delete the table, close the connection, and terminate

Listing 29 invokes the executeUpdate method to delete the table named myTable from the database named JunkDB.

 stmt.executeUpdate("DROP TABLE myTable");
con.close();
}catch( Exception e ) {
e.printStackTrace();
}//end catch
}//end main
}//end class Jdbc10

Listing 29

 

Then Listing 29 closes the connection (logs off the database) and terminates the program.


Tags: MySQL, JDBC

Originally published on http://www.developer.com.

Page 3 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel