JDBC Connection database code and procedures in Java development

Source: Internet
Author: User
Tags stmt

Tag: statement connection failed creat getc load driver class cut pass NULL

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) {       System. out. println (" driver class not found, load driver failed!") ");       E.printstacktrace ();}

After a successful load, an instance of the driver class is registered in the DriverManager class.

2. Provide the URL of the JDBC connection:

The connection URL defines the protocol, sub-protocol, and data source identity when the database is connected.

Writing form: 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: The tag locates the address of the database source and the connection port.

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. Create a connection to the database:

  to connect to a database, you need to request and obtain a connection object from Java.sql.DriverManager, which represents a connection to a database.

The DriverManager getconnectin (string URL, string username, string password) method is used 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:

//connect to MySQL database, user name and password are rootString 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 the SQL statement, you must obtain the Java.sql.Statement instance, which is divided into the following 3 types of statement instances:

(1) Execute a static SQL statement. 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 ();    = con.preparestatement (sql);    = Con.preparecall ("{call Demosp (?,?)} ") ;

5. Execute SQL statement:

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):

1, for the execution of INSERT, UPDATE or DELETE statements, returns the number of data bars to perform processing;

2, and SQL DDL statements, such as CREATE table and drop table, return 0, and throw an exception, so you need to put in the exception code snippet to catch the exception information.

(3) Execute (sqlString): Used to perform statements that return multiple result sets, multiple update counts, or a combination of both.

Specific implementation code:

ResultSet rs = stmt.executequery ("select * From ... " ) ;    int rows = stmt.executeupdate ("INSERT into ... " ) ;    = 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 returned by executing the query 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.next ()) {       = rs.getstring ("name");        = Rs.getstring (1/ / This method is more   efficient }   //(the column is numbered from left to right, and starting from 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:

Close the recordset, close the declaration, and then close the connection object.

if(rs! =NULL){//To close a record set    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 the Connection object    Try{conn.close (); }Catch(SQLException e) {e.printstacktrace (); }   }  

JDBC Connection database code and procedures in Java development

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.