JDBC Connection database code and steps in full Java development "blog Garden"

Source: Internet
Author: User
Tags stmt
JDBC Connection Database • Create a JDBC Connection database program that contains 7 steps: 1. Load JDBC Driver: Before connecting to the database, first load the drive to the JVM (Java Virtual Machine) of the database you want to connect to, through the JAV        The static method forname (String className) of the A.lang.class class is implemented. 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 successful loading, an instance of the driver class is registered to the DriverManager class.        2. The URL connection URL that provides the JDBC connection defines the protocol, child Protocol, and data source identity when connecting to the database.        • Written form: 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) 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 connection to a database • To connect to a database, you need to request and obtain a connection object that represents a connection to a database Java.sql.DriverManager. • Use the DriverManager getconnectin (string URL, string username, string password) method to pass in the specified path to the database to which you want to connect, the user name of the database, and the secret         Yards to get.          For example://Connect MySQL database, 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 ()  ;        &nbsp      4, create a statement          to execute an SQL statement, you must obtain a java.sql.Statement instance, and statement instances are divided into the following 3          types:            1, executing static SQL statements. Typically implemented through statement instances.           2, executing dynamic SQL statements. Typically implemented through PreparedStatement instances.           3, executing database stored procedures. Typically implemented through CallableStatement instances.         Specific implementation methods:             Statement stmt = con.createstatement ()  ;           PreparedStatement pstmt =  Con.preparestatement (SQL)  ;           callablestatement cstmt =                                   Con.preparecall ("{call demosp (?  , ?)}")  ;      5, Execute SQL statement        statement Interface provides three ways to execute SQL statements:executequery , Executeupdate        and execute         1, resultset  ExecuteQuery (string sqlstring): Execute the SQL statement of the query database            , Returns a result set (ResultSet) object.          2, intExecuteupdate (String sqlstring): Used to execute INSERT, UPDATE, or DELETE statements and SQL DDL statements, such as CREATE table and drop table 3, E       Xecute (SqlString): Used to execute statements that return multiple result sets, multiple update counts, or combinations of both. Code to implement: ResultSet rs = stmt.executequery ("SELECT * from ..."); introws = Stmt.executeupdate ("INSERT into ..."); BooleanFlag = Stmt.execute (String sql);          6, processing results of two cases: 1, the implementation of the update returned is 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, starting with column 1) 7, closing the JDBC object after the operation completes all the JDBC objects used are closed to release the JDBC resource, turn off the order harmony In the opposite order: 1, close recordset 2, close Declaration 3, close Connection object if(Rs!= NULL) {//closing recordsets Try{Rs.close (); } Catch(SQLException e)            {E.printstacktrace (); }              } if(stmt!= NULL) {//Close declaration Try{Stmt.close (); } Catch(SQLException e)            {E.printstacktrace (); }              } if(Conn!= NULL) {//Close Connection object Try{Conn.close (); } Catch(SQLException e)             {E.printstacktrace (); }              }

Original link: http://www.cnblogs.com/hongten/archive/2011/03/29/1998311.html

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.