The general steps for JDBC to connect to the database are as follows:
The premise is to import java.sql.*;
(1) : Load the driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLserverDriver");
(2) : establish a connection (via the driver manager)
Connection con = DriverManager.getConnection(URL, userName,userPwd);
(here URL = "jdbc:sqlserver://servername:1433; DatabaseName = database name")
(The last two parameters userName and userPwd are the user and password respectively, if not, you can leave it out)
(3) : Create Statement (created through Connection object),,
Statement st = con.createStatement();
//After the Statement is established, you can use the object st of the Statement to execute the sql statement. .
For example: st.executeUpdate("sql statement"). . . . For details, please refer to the API
(4) : close the connection
con.close();
Note: There will be some differences when connecting sql2000 and sql2005
The statement to load the driver and URL path in sql server 2000 is
String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sample";
The statement to load the driver and url in sql server 2005 is
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=sample";
----------------------------------------
JDBC connection database
? Create a program to connect to the database with JDBC, including 7 steps:
1. Load the JDBC driver:
Before connecting to the database, first load the driver of the database you want to connect to the JVM (Java Virtual Machine)
. The static method forName(String className) of the java.lang.Class class is implemented.
For example:
try{
//Load the driver class of MySql
Class.forName("com.mysql.jdbc.Driver") ;
}catch(ClassNotFoundException e){
System.out.println("Could not find the driver class, failed to load the driver !");
e.printStackTrace() ;
}
After successful loading, the instance of the Driver class will be registered in the DriverManager class.
2. Provide the URL of JDBC connection
? The connection URL defines the protocol, sub-protocol, and data source identifier when connecting to the database.
?Writing form: protocol: sub-protocol: data source identification
protocol: always start with jdbc in JDBC
sub-protocol: is the name of the bridge connection driver or database management system.
Data source identification: mark the address and connection port where the database source is found.
For example: (MySql connection URL)
jdbc:mysql:
//localhost:3306/test?useUnicode=true&characterEncoding=gbk ;
useUnicode=true: indicates the use of the Unicode character set. If characterEncoding is set to
gb2312 or GBK, this parameter must be set to true. characterEncoding=gbk: Character encoding method.
3. Create a database connection
? To connect to a database, you need to request and obtain a Connection object from java.sql.DriverManager,
which represents a database connection.
?Use the getConnectin(String url , String username ,
String password ) method of DriverManager to pass in the specified path of the database to be connected, the username and
password of the database to obtain.
For example:
//Connect to MySql database, both username and password are root
String url = "jdbc:mysql://localhost:3306/test" ;
String username = "root" ;
String password = "root" ;
try{
Connection con =
DriverManager.getConnection(url , username , password ) ;
}catch(SQLException se){
System.out.println("Database connection failed!");
se.printStackTrace() ;
}
4. Create a Statement
? To execute an SQL statement, you must obtain an instance of java.sql.Statement. The Statement instance is divided into the following three
types:
1. Execute static SQL statements. Usually implemented through a Statement instance.
2. Execute dynamic SQL statements. Usually implemented through a PreparedStatement instance.
3. Execute the database stored procedure. Usually implemented through a CallableStatement instance.
The specific implementation method:
Statement stmt = con.createStatement() ;
PreparedStatement pstmt = con.prepareStatement(sql) ;
CallableStatement cstmt =
con.prepareCall("{CALL demoSp(? , ?)}") ;
5. Execute SQL Statement
Statement interface provides three methods to execute SQL statement: executeQuery, executeUpdate
and execute
1. ResultSet executeQuery(String sqlString): execute query The SQL statement
of the database returns a result set (ResultSet) object.
2. int executeUpdate(String sqlString): used to execute INSERT, UPDATE or
DELETE statements and SQL DDL statements, such as: CREATE TABLE and DROP TABLE, etc.
3. execute(sqlString): used to execute multiple result sets, multiple updates A
statement that counts or a combination of the two .
Specific implementation code:
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;
int rows = stmt.executeUpdate("INSERT INTO ...") ;
boolean flag = stmt.execute(String sql) ;
6 ,process result
Two cases:
1. The number of records affected by this operation is returned when the update is executed.
2. The result returned by executing the query is a ResultSet object.
? ResultSet contains all the rows that meet the conditions in the SQL statement, and it provides
access to the data in these rows through a set of get methods.
? Use the access method of the ResultSet object to get the data:
while(rs.next()){
String name = rs.getString("name") ;
String pass = rs.getString(1) ; // This method compares Efficient
}
(columns are numbered from left to right and start from column 1)
7.
After closing the JDBC object operation, all used JDBC objects should be closed to release JDBC resources. The closing order is opposite to that of the
declaration :
1 , close the recordset
2, close the statement
3, close the connection object
if(rs != null){ // close the recordset
try{
rs.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
if(stmt != null){ // close statement
try{
stmt.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
if(conn != null) { // close the connection object
try{
conn.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
--------------------- ---------------------------------------
The steps are actually the same. Different databases have different Drivernames and urls. Novice students can remember them first.
------------------------------------------------
Share below:
Unified usage in JDBC
Class.for(jdbcDriverName);
Connection conn= DriverManager.getConnection(url,user,password);
MySQL
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://host:port/database","user","password");
Oracle database (thin mode)
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@host:port:databse","user","password");
Microsoft SQL Server
Class.forName("net.sourceforge.jtds.jdbc.Driver ");
Connection con = DriverManager.getConnection("jdbc:jtds:sqlserver://host:port/database","user","password");
or
Connection con = DriverManager.getConnection("jdbc:jtds:sybase://host:port/database","user","password");