In JavaProgramTo access the database through JDBC, follow these steps:
(1) load and register the JDBC driver for the database:
The following are four JDBC driver loading methods:
1) Load JDBC-ODBC DRIVER:Class. forname ("Sun. JDBC. ODBC. jdbcodbcdriver");//Built-in JDK, registered by default, no need to register
2) load and register oracledriverClass. forname ("Oracle. JDBC. Driver. oracledriver");
Java. SQL. drivermanager. registerdriver (NewOracle. JDBC. Driver. oracledriver ());
3) load and register mysqldriverClass. forname ("Com. MySQL. JDBC. Driver");
Java. SQL. drivermanager. registerdriver (NewCom. MySQL. JDBC. Driver)//Not required. MySQL Default and Registration
4) load and register sqlserver driverclass. forname ("com. Microsoft. JDBC. sqlserver. sqlserverdriver ");
Java. SQL. drivermanager. registerdriver (new COM. Microsoft. JDBC. sqlserver. sqlserverdriver ());
Note: The MySQL driver Driver Class in the old version is org. Git. Mm. MySQL. Driver. This class is retained in the new version, and the new COM. MySQL. JDBC. Driver Class is recommended.
(2) establish a connection with the databaseConnection con=Java. SQL. drivermanager. getconnection (dburl, user, password );
Getconnection () has three parameters:
1) dburl indicates the jdbcurl of the linked data
2) User Name
3) password
The general form of dburl is JDBC: drivertype: driversubtype: // parameters.
Drivertype indicates the driver type. Driversubtype is an optional parameter. parameters is usually used to set the IP address, port number, and Database Name of the database server.
Below are the jdbcurl forms of several common databases:
JDBC-ODBC driver |
JDBC: ODBC: datasource |
Oracle Link |
JDBC: oracle: thin: @ localhost: 1521: Sid |
Sqlserver Database Link |
JDBC: Microsoft: sqlserver: // localhost: 1433: databasename = bookdb |
MySQL Link |
JDBC: mysql: // loaclhost: 3306/bookdb |
(3) create a statement object and prepare to call the SQL statement:Statement stmt=Con. createstatement ();
(4) Call the SQL statement:String SQL= "";
Resultset rs=Stmt.exe cutequery (SQL );
(5) access the record set in resultset:While(Rs. Next ()){
String col1=Rs. getstring (1);
}
(6) Disable resultset, statement, and connection objects Rs. close ();
stmt. close ();
con. close ();