Code and steps for JDBC Connection database in Java development
Create a JDBC Connection database program, a total of 7 steps:1. Load Database driverBefore connecting to the database, you first load the drive to the JVM for the database you want to connect to, which is implemented by the static method forname (String className) of the Java.lang.Class class. Com.mysql.jdbc.Driver in the Mysql-connector-java-5.1.26-bin.jar package for example:
Try{//loading MySQL driver class Class.forName ("Com.mysql.jdbc.Driver"); }Catch(ClassNotFoundException e) {System.out.println ("Driver class not found, load driver failed.") "); E.printstacktrace (); }
After a successful load, an instance of the driver class is registered to the DriverManager class.2, provide the URL of the database connection
A connection URL defines a protocol, a child protocol, and a data source identity when connecting to a database. Writing: Protocol: Sub-Protocol: Data Source identification protocol: Always start with JDBC in JDBC: A bridge-connected driver or database management system name. Data source ID: Tag to locate the address and connection port of the database source. For example: (MySQL's connection url) String URL =jdbc:mysql://192.168.1.100/test?useunicode=true&characterencoding=utf-8; Useunicode=true: Indicates the use of the Unicode character set. If Characterencoding is set to Utf-8,characterencoding=utf-8: Character encoding.3. Create a database connection
To connect to a database, you need to request the Java.sql.DriverManager and get the Connection object, which represents a connection to a database. Use the DriverManager getconnectin (string URL, string username, string password) method to obtain the path to the specified database to connect to, the user name and password of the database. For example://Connect MySQL database, username is root, password is 123456 String url = "Jdbc:mysql://192.168.1.100/test"; String username = "root"; String password = "123456";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 SQL statements, you must obtain Java.sql.Statement instances, statement instances are divided into the following 3 types: 1, executing static SQL statements. Typically implemented through statement instances. 2, execute dynamic SQL statements. Typically implemented through PreparedStatement instances. 3, execute database stored procedures. Typically implemented through CallableStatement instances. Specific implementation methods: Statement stmt = conn.createstatement () ; preparedstatement pstmt = Conn.preparestatement (SQL) ; callablestatement cstmt = Conn.preparecall ("{call demosp (? , ?)}")  ;&NBSP
5, executing SQL statements
The statement interface provides three ways to execute SQL statements: ExecuteQuery, executeupdate, and execute
1, ResultSet executequery (String sqlstring): Executes the SQL statement that queries 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
3. Execute (sqlstring): Used to execute statements that return multiple result sets, multiple update counts, or combinations of both.
Specific code to implement:
ResultSet rs = stmt.executequery ("SELECT * from ..."); int rows = stmt.executeupdate ("INSERT into ...");
boolean flag = Stmt.execute (String sql);
For example:
String sql = "SELECT * from user";
ResultSet rs = stmt.executequery (SQL); 6, processing results
Two cases: 1, the execution of the update returns the number of records affected by this operation. 2. The result returned by the execution query is a ResultSet object. resultset contains all the rows that conform to the conditions in the SQL statement, and it provides access to the data in those rows through a set of Get methods. • Get data using the access method of the result set (ResultSet) object: while (Rs.next ()) {String name = rs.getstring (' name '); String pass = rs.getstring (1); This method is more efficient} (columns are numbered from left to right, and starting from column 1)
7. Close JDBC ObjectAfter the operation is complete, all the JDBC objects used will be closed to release the JDBC resource, and the shutdown order and the declaration order are reversed: 1. Close the recordset
2, close the Declaration 3, close the Connection objectif(Rs!=NULL) {//closing recordsetsTry{Rs.close (); }Catch(SQLException e) {E.printstacktrace (); } }if(stmt!=NULL) {//Close declarationTry{Stmt.close (); }Catch(SQLException e) {E.printstacktrace (); } }if(Conn!=NULL) {//Close Connection objectTry{Conn.close (); }Catch(sqlexception e) { E.printstacktrace () ; } }