JDBC uses database URLs to clear the database driver. The database URL is similar to the universal URL, but Sun is simplified when it is defined, and its syntax is as follows:
JDBC :: [Node] / [database]
Where Subprotocal defines the drive type, Node provides the location and port number of the network database, followed by the optional parameters. E.g:
String url = "JDBC: inetdae: MyServer: 1433? Language = US-English & SQL7 = TRUE
Indicates the MyServer database server on the port 1433 port using the inetdae driver, selecting the language for US English, the database version is MSSQL Server 7.0.
Java applications are loaded into a driver class by specifying DriverManager. The syntax is as follows:
Class.Forname ("");
or
Class.Forname (""). NewInstance ();
Then DriverManager creates a specific connection:
Connection Connection = DriverManager.getConnection (URL, Login, Password);
The Connection interface connects the database by specifying the database location, login name and password. CONNECTION interface creates a Statement real
Example to do the required query:
Statement Stmt = Connection.createStatement ();
Statement has a variety of methods (APIs), such as ExecuteQuery, Execute, etc., can return the result set of queries. The result set is an RESULTSET object. The specific view can be viewed through the JDBC development document. Can download on Sun's site
The following example shows:
Import java.sql. *; // Enter JDBC Package
String Url = "JDBC: inetdae: myserver: 1433"; // host name and port
String login = "user"; // login name
String password = ""; // password
Try {
Drivermanager.setlogstream (system.out); file: / / open a stream for display some information
FILE: // Call the driver, its name is com.inet.tds.tdsdriver
File: //class.forname ("com.inet.tds.tdsdriver);
File: // Set timeout
Drivermanager.setlogintimeout (10);
File: // Open a connection
Connection Connection = DriverManager.getConnection (URL, Login, Password);
File: // Get the database driver version
DatabaseMetadata conMd = connection.getMetadata ();
System.out.println ("driver name: / t" conMd.getdrivername ());
System.out.println ("Driver Version: / T" ConMd.getdriverVersion ());
File: // Select the database
Connection.SetCatalog ("MyDatabase");
File: // Create Statement
Statement St = connection.createstatement (); file: // Execute Query
ResultSet RS = St.executeQuery ("SELECT * from myTable");
File: // Get the result, output to the screen
While (rs.next ()) {
For (int J = 1; j <= rs.getMetadata (). getColumnCount (); J ) {
System.out.print (Rs.GetObject (j) "/ t");
}
System.out.println ();
}
File: // Close the object
St.close ();
Connection.Close ();
} Catch (exception e) {
E.PrintStackTrace ();
}