A summary of JDBC Connection database code and procedures in Java

Source: Internet
Author: User
Tags stmt

JDBC Connection Database
? Create a program that connects to the database in JDBC with 7 steps:
1. Load the JDBC driver:
Before connecting to a database, you first load the driver of the database you want to connect to the JVM (Java Virtual machine), which is implemented by the static method forname (String className) of the Java.lang.Class class.
For example:

 try  { //  load MySQL driver class  class.forname (" Com.mysql.jdbc.Driver ");  catch   (classnotfoundexception e) {Syst Em.out.println ( "Driver class not found, load driver failed!")             ");          E.printstacktrace (); } 

        NOTE: After a successful load, an instance of the driver class is registered to the DriverManager class.
       2, providing a URL to a JDBC connection
? The connection URL defines the protocol, sub-protocol, and data source identity when the database is connected.
? Writing: Protocol: Sub-Protocol: Data source identification
        protocol: Always start with JDBC in JDBC
      Sub-Protocol: A bridge-connected driver or database management system name.
      Data source identification: Tags Locate the address and connection port of the database source.
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: The character encoding method.
       3, creating a connection to the database
? To connect to the database, The connection object needs to be requested and obtained from Java.sql.DriverManager, which represents a connection to a database.
? Use DriverManager's Getconnectin (string URL, string username, string password) method to pass in the path of the specified database to be connected, the user name of the database, and the password to obtain.
For example:

String url = "Jdbc:mysql://localhost:3306/test";           = "root" ;      = "root"try= drivermanager.getconnection (URL, username, password);  } Catch (SQLException se) {  System.out.println ("Database connection failed! ");  

4. Create a statement
To execute the SQL statement, you must obtain the Java.sql.Statement instance, which is divided into the following 3 types of statement instances:
1. Execute static SQL statements. Typically implemented through statement instances.
2. Execute dynamic SQL statements. Typically implemented through PreparedStatement instances.
3. Execute the database stored procedure. Typically implemented through CallableStatement instances.
The specific implementation method:
Statement stmt = Con.createstatement ();
PreparedStatement pstmt = con.preparestatement (sql);
CallableStatement cstmt = Con.preparecall ("{Call Demosp (?,?)}");
5. Execute 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 and 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 statements that return multiple result sets, multiple update counts, or both.
Specific implementation code:
ResultSet rs = stmt.executequery ("SELECT * from ...");
int rows = Stmt.executeupdate ("INSERT into ...");
Boolean flag = Stmt.execute (String sql);
6. Processing Results
Two cases:
1. The number of records affected by this operation is returned by performing the update.
2. The result of executing the query returned is a ResultSet object.
? ResultSet contains all 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.getstring ("name"//

(columns are numbered from left to right and start with column 1)
7. Close the JDBC object
After the operation is complete, all the JDBC objects used are closed to release the JDBC resource, and the order of closing and declaration is reversed:
1. Close record set
2. Closing the statement
3. Close the Connection object

 if(rs! =NULL){//To close a record setTry{rs.close ();}Catch(SQLException e) {e.printstacktrace ();}} if(stmt! =NULL){//Close DeclarationTry{stmt.close ();}Catch(SQLException e) {e.printstacktrace ();}} if(Conn! =NULL){//Close the Connection objectTry{conn.close ();}Catch(SQLException e) {e.printstacktrace ();}}

The example demo code is as follows:

1  PackageCOM.LW;2  3 Importjava.sql.Connection;4 ImportJava.sql.DriverManager;5 Importjava.sql.PreparedStatement;6 ImportJava.sql.ResultSet;7 Importjava.sql.SQLException;8 /**9  *Ten  * @authorlw</br> One * @date 2012-7-16 A  * -  */ -  Public classJdbctest { the      Public Static voidMain (string[] args) { -String Driver = "Com.mysql.jdbc.Driver"; -String dbName = "Spring"; -String Passwrod = "root"; +String userName = "root"; -String url = "jdbc:mysql://localhost:3306/" +DbName; +String sql = "SELECT * from Users"; A   at         Try { - Class.forName (driver); -Connection conn =drivermanager.getconnection (URL, userName, passwrod); -PreparedStatement PS =conn.preparestatement (SQL); -ResultSet rs =ps.executequery (); -              while(Rs.next ()) { inSYSTEM.OUT.PRINTLN ("ID:" + rs.getint (1) + "Name:" + rs.getstring (2) + "Password:" + rs.getstring (3)); -             } to   +             //To close a record set -             if(rs! =NULL) { the                 Try { * rs.close (); $}Catch(SQLException e) {Panax Notoginseng e.printstacktrace (); -                 } the             } +   A             //Close Declaration the             if(PS! =NULL) { +                 Try { - ps.close (); $}Catch(SQLException e) { $ e.printstacktrace (); -                 } -             } the   -             //Close linked ObjectsWuyi             if(Conn! =NULL) { the                 Try { - conn.close (); Wu}Catch(SQLException e) { - e.printstacktrace (); About                 } $             } -   -}Catch(Exception e) { - e.printstacktrace (); A         } +     } the   -}

==================== printing results are as follows: ====================

      *********   id : 2 name:lw  password: 123456   **********

A summary of JDBC Connection database code and procedures in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.