JDBC Connection database code in full Java development ...

Source: Internet
Author: User

JDBC Connection Database

• Create a program that connects the database with JDBC, which contains 7 steps:

1. Load JDBC Driver:

Before you connect to a database, you first load the drive to the JVM (Java Virtual Machine) of the database you want to connect to.

This 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 to the DriverManager class.

2. Provide the URL of the JDBC connection

• The connection URL defines the protocol, child Protocol, and data source identity when connecting to a database.

• Writing form: Protocol: Sub-Protocol: Data source identification

Protocol: Always start with JDBC in JDBC

Sub-Protocol: The driver for the bridge connection or the name of the database management system.

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 argument must be set to true. CHARACTERENCODING=GBK: Character encoding method.

3, create the connection of the database

• To connect to the database, you need to request and get the connection object to the Java.sql.DriverManager.

This object represents a connection to a database.

• Use DriverManager's getconnectin (string URL, string username,

The String password method passes in the path of the specified database to which you want to connect, the user name of the database, and

Password to obtain.

For example:

Connect to 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 ();

}

4. Create a statement

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

Types of:

1, execute 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.

Specific ways to achieve:

Statement stmt = Con.createstatement ();

PreparedStatement pstmt = con.preparestatement (sql);

CallableStatement cstmt =

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): Executing the SQL statement of the query database

, returns a result set (ResultSet) object.

2, int executeupdate (String sqlstring): Used to perform INSERT, UPDATE, or

Delete statements and SQL DDL statements, such as CREATE table and drop table

3. Execute (sqlstring): Used to perform returns of multiple result sets, multiple update counts, or combination of both

Statement.

Specific code to implement:

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 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 a set of get methods that provide the

Access to data in the row.

• 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 Object

After the operation is complete, all JDBC objects used are closed to release the JDBC resource, turn off the order harmony

The order of the Ming is the opposite:

1, close the recordset

2. Close the statement

3, close the Connection object

if (Rs!= null) {//close Recordset

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 ();

}

}

//------------------------------------------------------------------------------------------------------------- -------------------

Package com.b510;

Import java.sql.Connection;

Import Java.sql.DriverManager;

Import java.sql.PreparedStatement;

Import Java.sql.ResultSet;

Import java.sql.SQLException;

public class Jdbctest {

public static void Main (string[] args) {

String Driver = "Com.mysql.jdbc.Driver";

String dbname = "Spring";

String Passwrod = "root";

String userName = "root";

String url = "jdbc:mysql://localhost:3308/" + dbname;

String sql = "SELECT * from users";

try {

Class.forName (driver);

Connection conn = drivermanager.getconnection (URL, userName,

Passwrod);

PreparedStatement PS = conn.preparestatement (SQL);

ResultSet rs = Ps.executequery ();

while (Rs.next ()) {

SYSTEM.OUT.PRINTLN ("ID:" + rs.getint (1) + "Name:"

+ rs.getstring (2) + "Password:" + rs.getstring (3));

}

Turn off recordsets

if (Rs!= null) {

try {

Rs.close ();

catch (SQLException e) {

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.