First, the concept
1. In order to make a database program operating on the operating table in the database, each database will provide a drive connection and operation of the database, and each database driver are not the same, for example, using mysql mysql database driver , oracle database using oracle drive, so if we write a program which day you want to change the database, that will be very easy, because all the code to connect to the database must be re-written. SUN company in order to simplify. Unified operation of the database, or specification defines a standard set of java database operation, this specification is JDBC.
2.JDBC full name: Java Data Base Connectivity (java database connectivity), it mainly consists of interfaces. We in the development process, as long as you realize it can be very appropriate interface to connect.
3. When we develop JDBC applications, but also need to import the appropriate database driver jar package , these drivers jar package is written by the company's own database.
Second, the premise write JDBC applications (programs need to connect to the database) preparation
1. The first thing to determine which database instance is connected, for example, mysql, we can create a database, then create a table in the library, to insert some data in the table, I am here to provide some created in the mysql database a library, and tables and data sql statement, which is connected to the following tables and the database repository operations.
create database test; / * create a database named Test * / use Test; / * use the database to the database or switching * / Create Table Book ( ID int Primary Key AUTO_INCREMENT, / * column: id, Type: int starts from 0, automatically increase, Note: the primary key * / name VARCHAR (40) the NOT NULL, / * column: name, type: VARCHAR, Note: non-empty * / author VARCHAR (40) the NOT NULL, / * column: author , type: VARCHAR, Note: non-empty * / Prices Double the NOT NULL / * column: Prices, type: Double, Note: non-empty * / ); / * Create a table named book * / / * insert four famous data * / INSERT INTO Book (ID, name, author, Prices) values (null, 'Journey to the West', 'WuChengEn', 25.00); INSERT INTO Book (ID, name, author, Prices) values (null, ' Water Margin ',' Shinai ', 30.00); INSERT INTO Book (ID, name, author, Prices) values (null,' Dream of the Red ',' Cao Xueqin ', 35.00); INSERT INTO Book (ID, name, author, Prices) values (null,' Three Kingdoms', 'Luo Guanzhong', 40.00);
2. Create a java project, and then import the mysql driver jar package come in, that is added to the library program is running, the specific driver jar package, we can find in the installation directory database, or have your own online download corresponding database driver jar package
Third, the step of connecting a database operation analysis
(1) Registration Database Driver
Although we are just at the time of the new projects will drive the java jar package mysql database import came in, but JBDC do not know there is a driver package, then we need this driver package to JBDC to manage it, we can use java. DriverManager tools in sql package provides registerDriver (driver driver) method to register in JDBC this data-driven, this registerDriver (driver driver) method requires a driver object, the driver class itself is an interface provided by JDBC, our which has been driven implements this interface , so we just need to write the following code can be achieved registration database driven functionality
import java.sql.DriverManager; // interface class is to be imported package DriverManager.registerDriver (new Driver ());
(2) acquire (create) a database connection
We registered a good database-driven, and not connected to the database, in the past, we do not care in the CMD window, through visual database management tools to operate the database, we need to connect to the database server, java program to connect the database is no exception, the Java here program is equivalent to the client, only connect to the database service in order to operate the database
The client all interact with the database through the connection objects are accomplished , commonly used methods of this object:
createStatement (): create objects sql statement sent to the database.
prepareStatement (sql): sql create precompiled sent to the database
Here we can create a database connection object through the DriverManager tools in the getConnection (url, user, password) method, this method requires three arguments:
User: User name for the database
Password: user password
URL: database server address, URL different wording different databases, I provide the URL address written three mainstream database here:
Oracle写法:jdbc:oracle:thin:@localhost:1521:sid
SqlServe写法:jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sid
MySql wording: jdbc: mysql: // localhost: 3306 / sid
Shorthand url address of Mysql: jdbc: mysql: /// sid
NOTE: The next sid is the instance name of the database (database name used)
import java.sql.Connection; // interface class is imported package Connection conn = DriverManager.getConnection ( "jdbc: mysql: // localhost: 3306 / test", "root", "root"); // herein is a mysql database, user name and password are root named test
(3) create a transport object
We have already created a connection to the database has been connected to the database, but if we want to operate the database, we need to use sql statement, and how do we use the sql statement in java program to operate the database yet, here we are objects need a transmitter to transmit sql statement to the database to perform . CreateStatement mentioned above, there is a class in the Connection () method to create a transfer object
import java.sql.Statement; // interface class is imported package Statement stat = conn.createStatement ();
(4) using a transmission object transmitted sql statement to the database to perform operations, returning the result set with the result
There are many ways java.sql.Statement who transfer sql statement: which is the most used
executeQuery (String sql): for sending a query to the data.
executeUpdate (String sql): for sending a database to insert, update, or delete statement
execute (String sql): used to send any sql statement to the database
import java.sql.ResultSet; // interface class to be imported package ResultSet rs = stat.executeQuery ( "select * from book"); // transmit a query, the query data is all tuples book table
(5) traverse the result set, and get query object
Jdbc program for executing ResultSet results represent Sql statement. When Resultset package the results collected similar manner as the table . ResultSet object maintains a pointer to a data table row cursor , the initial time, the cursor before the first row , the ResultSet.next call () method, so that the cursor can be directed to a particular data line, the data obtaining method call line.
Since for packaging ResultSet execution result, it is the object to provide a method for acquiring data get:
Get the specified type of data, for example:
getString(int index)
getString(String columnName)
ResultSet also provides a method for the result set rolling:
next (): move to the next line
Previous (): move to the previous row
absolute (int row): to a specific line
beforeFirst (): the front of the mobile resultSet.
afterLast (): move to the rearmost resultSet.
while(rs.next()) { String name = rs.getString("name"); System.out.println(name); }
(6) closes the connection (after first created closed)
Jdbc program has run, remember to release the program in operation, those that interact with the database was created as these objects are usually ResultSet, Statement, and Connection objects.
In particular Connection object, it is very scarce resources, must be released immediately after use, if not timely Connection, right close, can easily lead to system downtime. Use doctrine Connection is created as late as possible, as much as possible early release.
rs.close(); stat.close(); conn.close();
Initial full source code
Package jdbcDemo. 1; 2 / **************************** . 3 * connected to the first edition program database 4 ********* ******************************************************** / . 5 Import the java.sql.Connection; . 6 Import the java.sql.DriverManager; . 7 Import the java.sql.ResultSet; . 8 Import java.sql.SQLException; import the java.sql.Statement. 9; 10 // can not be introduced in java.sql driver Interface, to import driver jar package interface implementation class, in order to register the only database corresponding driver 11 import com.mysql.jdbc .Driver; 12 is JDBCTest {public class 13 is public static void main (String [] args) throws SQLException { 14 // registration database driver. 1. 15 DriverManager.registerDriver (new new driver ()); . 16 // 2 connection access to the database DriverManager.getConnection Connection conn = 17 ( "jdbc: MySQL: // localhost:? 3306 / useSSL the Test = false", "root", "root"); . 18 3 // create a transport object 19 Statement stat = conn. the createStatement (); 20 is //. 4 using the transfer object transfer sql statement to the database to perform operations, the result returned by the result set. 21 is the resultSet stat.executeQuery RS = ( "SELECT * from Book"); . 22 is traversed. 5 // the result set, and acquires the search results 23 is the while (rs.next ()) { 24 rs.getString String name = ( "name"); 25 System.out.println (name); 26 is} . 27 // close the connection. 6 ( after opening the first off) 28 rs.Close (); 29 stat.close (); 30 conn.Close (); 31 is} 32}
Datasheet view and run results:
Fourth, the initial database connection problems appear in the program
1-- registration database-driven method appears twice due to improper registration procedures versatile low
We can see the following code in the source view Driver class, we can see from the line 7 code, MySQL in the realization Driver class to register itself once, and we have registered in the program once, resulting in two registration secondary
When we register your drive, you need to import mysql driver Driver class jar package has been achieved, so that the program and the specific database to bind together, the versatility of the program would be lower, if we want to switch databases, have to change Source
1 public class Driver extends NonRegisteringDriver implements java.sql.Driver { 2 // 3 // Register ourselves with the DriverManager 4 // 5 static { 6 try { 7 java.sql.DriverManager.registerDriver(new Driver()); 8 } catch (SQLException E) { 9 throw new RuntimeException("Can't register driver!"); 10 } 11 }
Repair method:
Use Class.forname () method of the class mysql Driver already implemented loaded into the program, due Driver class implementing the interface used in a static block of code, and the static block of code is executed only once at the time the class is loaded, i.e., to ensure that the database driver will only be registered once, and do not drive in the drive to import mysql class package, versatile program to improve
Class.forName("com.mysql.jdbc.Driver");
2-- ignore the program may throw exceptions (the biggest problem)
We in the implementation of the program, many of its method invocation throws an exception, if it throws an exception, did not do the appropriate treatment (catch this exception) then the program will break execution, Statement object and the Connection object is not closed and we know that Connection object, it is very scarce resources, it must be released immediately after use, if not timely Connection, right close, can easily lead to system downtime, so we need to ensure that no matter which step in the procedure leading to abnormal program interruption, the connection is closed code will be executed, then we will think of exception handling in the finally block, we can throw an exception up, but first try to live and then catch an exception, the last execution finally block
After the changes, we found that each close () are suggestive of abnormalities to be treated, and we also directly try / catch each exception
The modified source code:
Package jdbcDemo. 1; 2 / **************************** . 3 connected to a modified version of the database program * 4 ******** ************************************************** / . 5 Import the java.sql.Connection; . 6 Import the java.sql.DriverManager; . 7 Import the java.sql.ResultSet; . 8 Import java.sql.SQLException ; . 9 Import the java.sql.Statement; 10 . 11 {public class JDBCTest 12 is public static void main (String [] args) { 13 is Conn Connection = null; 14 the Statement STAT = null; 15 the ResultSet RS = null; 16 {the try . 17 / . / 1 driver registration database 18 is the Class.forName ( "com.mysql.jdbc.Driver"); .. 19 // 2 to obtain the connection database DriverManager.getConnection conn = 20 ( "? Jdbc: MySQL: // localhost: 3306 / useSSL the Test = false", "root", "root"); 21 // 3 create a transport object. 22 STAT = conn.createStatement ( ); 23 // 4 perform transmission using the transfer object sql statement to the database operations, the result sets are returned with the result 24 stat.executeQuery RS = ( "SELECT * from Book"); .. 5 // 25 traverse the result set, and acquiring a query result 26 is the while (rs.next ()) { 27 rs.getString String name = ( "name"); 28 System.out.println (name); 29} 30} the catch (Exception E) { 31 is E. printStackTrace (); 32} {the finally 33 is //. 6.Close the connection (first off after opening) 34 try { 35 rs.close(); 36 } catch (SQLException e) { 37 e.printStackTrace(); 38 } 39 try { 40 stat.close(); 41 } catch (SQLException e) { 42 e.printStackTrace(); 43 } 44 try { 45 conn.close(); 46 } catch (SQLException e) { 47 e.printStackTrace(); 48 } 49 } 50 } 51 }
Fifth, the revised program exceptions are ignored
Unusual problem
1. Since we first declared at the beginning of the program refers to three objects, and are assigned to null, if this step in the implementation of the program to the registration database to throw an exception, then the finally block to catch the exception, It was found that ResultSet object references, and references cited Connection object is null Statement object, invoke methods on this object throws null pointer exception
2. use Close () This method who is also abnormal , if we do not do the appropriate exception handling, or objects that can not be properly closed
Solution
1 --- To prevent null pointer exception, we can first determine whether the referenced object which is null, if not null, exception handling code is executed
2 --- each close () plus finally a static block, the reference value of each respective object is set to null after the exception process, the principle is: If the program is executed to close () method throws an exception and , the last finally block execution, set the value to the application object is null, because the object has no references pointing to it, it becomes a garbage objects, JVM garbage collector will reclaim the object resources, this object will close the
Exception handling after the final source code:
Package jdbcDemo. 1; 2 / **************************** . 3 * No abnormal connection database program Version 4 ******* ******************* / . 5 Import the java.sql.Connection; . 6 Import the java.sql.DriverManager; . 7 Import the java.sql.ResultSet; . 8 Import the java.sql. SQLException; . 9 Import the java.sql.Statement; 10 . 11 {public class JDBCTest 12 is public static void main (String [] args) { 13 is Conn Connection = null; 14 the Statement STAT = null; 15 the ResultSet RS = null; 16 {the try . 17 // Register database driver 1 18 is the Class.forName ( "com.mysql.jdbc.Driver"); .. 19 // 2 to obtain a connection database DriverManager.getConnection conn = 20 ( "? Jdbc: MySQL: // localhost: 3306 / useSSL the Test = false", "root", "root"); 21 // 3 create a transport object. 22 STAT = conn.createStatement ( ); 23 // 4 perform transmission using the transfer object sql statement to the database operations, the result sets are returned with the result 24 stat.executeQuery RS = ( "SELECT * from Book"); .. 5 // 25 traverse the result set, and acquiring a query result 26 is the while (rs.next ()) { 27 rs.getString String name = ( "name"); 28 System.out.println (name); 29} 30} the catch (Exception E) { 31 is E. printStackTrace (); 32} {the finally 33 is //. 6.Close the connection (first off after opening) 34 if(rs != null) { 35 try { 36 rs.close(); 37 } catch (SQLException e) { 38 e.printStackTrace(); 39 } finally { 40 rs = null; 41 } 42 } 43 if(stat != null) { 44 try { 45 stat.close(); 46 } catch (SQLException e) { 47 e.printStackTrace(); 48 }finally { 49 stat = null; 50 } 51 } 52 if(conn != null) { 53 try { 54 conn.close(); 55 } catch (SQLException e) { 56 e.printStackTrace(); 57 }finally { 58 conn = null; 59 } 60 } 61 } //--finally 62 } //--main 63 }//--class
to sum up:
Here, I just put all the anomalies processed, but the program's versatility is not particularly high , because Driver class name of the database connection used, URL, user and password are written in the program, we can actually write in a text file by reading each file to get database-specific connection parameters.
There is the actual development process, the program code to connect to the database will generally write a tool in class, when we want to operate the data in the database, only need to call this tool class on it, do not always write so many codes
Next, I will update how to connect a database of information stored in a text file, and then read this file to operatively coupled to the database, but I will also take this program to modify a connection to the database tools