Java JDBC Connection Database

Source: Internet
Author: User
Tags stmt

JDBC (Java database Connectivity,java) is an API for executing SQL statements that provides unified access to a variety of databases.

Create a program that connects to the database in JDBC with 5 steps:

1. Load the JDBC Driver

Before connecting to the database, you first load the driver of the database you want to connect to the JVM, implemented by the static method forname (String className) of the Java.lang.Class class. When the driver class is loaded, an instance of the driver class is registered to DriverManager.

1 Try {2 class.forname ("Com.mysql.jdbc.Driver"); 3 }catch4   5 }

2. 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.

Connection 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) {   }

Note: The URL of the JDBC connection

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.

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 statement

To execute an SQL statement, you must obtain the Java.sql.Statement instance, which is divided into the following 3 types:

Statement: Executes a static SQL statement. Cases:

Statement stmt = Con.createstatement ();

PreparedStatement: Executes a dynamic SQL statement. Cases:

PreparedStatement pstmt = conn.preaprestatement (sql);

CallableStatement: Executes the database stored procedure. Cases:

CallableStatement cstmt = Con.preparecall ("{Call Demosp (?,?)}");   

4. Execute SQL statements

The statement interface provides three ways to execute SQL statements: ExecuteQuery, Executeupdate, and execute:

ResultSet executeQuery (String sqlString): Executes the SQL statement that queries the database and returns a result set (ResultSet) object.

ResultSet rs = stmt.executequery ("SELECT * from ...");

int executeupdate (String sqlString): Used to execute INSERT, UPDATE, or DELETE statements, as well as SQL DDL statements such as CREATE table and drop table, etc.

int rows = stmt.executeupdate ("INSERT into ...");   

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

boolean flag = Stmt.execute (String sql);  

Note:

Two cases of processing results:

(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");    // // (columns are numbered from left to right and start with column 1)     }      

5.

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) Closing the recordset

(2) Closing the Declaration

(3) Closing the Connection object

 if(rs! =NULL){//To close a record set Try{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 (); }   }  

JDBC is actually a low-level interface, which is used to invoke SQL commands directly. Above it can build more advanced interfaces and tools, the advanced interface is a user-friendly interface, this API in the background is converted to a low-level interface such as JDBC.

Java JDBC Connection Database

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.