This section describes how to connect a JdbcRowSet object to a database server with a connection URL.
If a JdbcRowSet object is created without a connection to the database server,
you can provide a connection URL string by calling the setUrl() method.
A connection object will be created later by the JdbcRowSet object with DriverManager when you call the execute() method.
Here is a sample sequence of method calls:
// Creating a JdbcRowSet object wihout connection
JdbcRowSet jrs = new JdbcRowSetImpl();
// Provide a connection URL for future use
jrs.setUrl("connection_url");
// Provide a SQL statement for future use
jrs.setCommand("SQL_statement");
// Create a connnection using DriverManager
// Execute the SQL statement
jrs.execute();
Note that the name of method setUrl() is very confusing with another method setURL(), which sets a URL value to a parameter.
Note also that the connection URL and user information can also be provided through another constructor:
JdbcRowSet jrs = new JdbcRowSetImpl("connection_url",
"user", "password");
To test connection method, I wrote the following tutorial program:
/**
* MySqlRowSetConnectionUrl.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class MySqlRowSetConnectionUrl {
public static void main(String [] args) {
try {
// Load the JDBC driver class. Needed for JDBC 3.0 drivers
Class.forName("com.mysql.jdbc.Driver") ;
// Get a new JdbcRowSet object with Run's implementation
javax.sql.rowset.JdbcRowSet jrs
= new com.sun.rowset.JdbcRowSetImpl();
// Set the connection URL for the DriverManager
jrs.setUrl("jdbc:mysql://localhost/HerongDB"
+"?user=Herong&password=TopSecret");
// Set a SQL statement
jrs.setCommand("SELECT 'Hello world!'");
// Connect and run the statement
jrs.execute();
// Get the result
jrs.next();
System.out.println("Result: "+jrs.getString(1));
// Close resource
jrs.close();
} catch (Exception e) {
System.err.println("Exception: "+e.getMessage());
}
}
}
Make sure the MySQL server is running on the local machine, then run this program.
The result confirms that the connection is working.
C:\>javac -cp .;\local\lib\rowset.jar MySqlRowSetConnectionUrl.java
MySqlRowSetConnectionUrl.java:16:
warning: com.sun.rowset.JdbcRowSetImpl is Sun proprietary API and
may be removed in a future release
= new com.sun.rowset.JdbcRowSetImpl();
^
1 warning
C:\>java -cp .;\local\lib\rowset.jar;
\local\lib\mysql-connector-java-5.0.7-bin.jar
MySqlRowSetConnectionUrl
Result: Hello world!
Notice that a warning message was given at the compilation time.