JDBC Steps and simple implementation code _java

Source: Internet
Author: User
Tags stmt

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

1. Load JDBC Driver:

Before connecting to a database, you first load the drive to the JVM (the Java Virtual machine) of the database you want to connect to, which is implemented by the static method forname (String className) of the Java.lang.Class class.

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

Represents 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 a database, you need to request the Java.sql.DriverManager and get the Connection object, which represents a connection to a database.

• Use DriverManager getconnectin (string URL, string username, string password)

method is obtained by passing in the path of the specified database to which you want to connect, the username and password of the database.

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

4. Create a statement

• To execute an SQL statement, you must obtain a java.sql.Statement instance, and the statement instance is divided into the following 3 categories:

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 =

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, 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

3. Execute (sqlstring): Used to execute statements that return multiple result sets, multiple update counts, or combinations of both.

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 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, 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, in reverse order and in the declaration order:

1, close the recordset
2. Close the statement
3, close the Connection object

Package me.clfeng.jdbc;

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;

public class DBHelper {public

  static final String url = ' Jdbc:mysql://localhost:3306/mybatis ';
  public static final String name = "Com.mysql.jdbc.Driver";
  public static final String username = "root";
  public static final String password = "123456";

  public Connection conn = null;
  Public PreparedStatement statement = null;

  Public dbhelper (String sql) {
    try {
      class.forname (name);//Specify connection type
      conn = Drivermanager.getconnection ( URL, username, password)//get connection
      statement = conn.preparestatement (SQL);//Ready to execute statement
    } catch (Exception e) {  
      e.printstacktrace ();
    }
Release resource public
  void Close () {
    try {
      this.conn.close ();
      This.statement.close ();
    } catch (Exception e) {
      e.printstacktrace ();}}}

Test code:

Package me.clfeng.jdbc;

Import Java.sql.ResultSet;

public class Jdbctest {
  
  static String sql = null;
  static DBHelper dbhelper = null;
  static ResultSet ResultSet = null;

  public static void Main (string[] args) {
    sql = ' SELECT * from user ';
    DBHelper = new DBHelper (SQL);

    try {
      resultSet = DbHelper.statement.executeQuery ()//EXECUTE statement, get result set while
      (Resultset.next ()) {
        int id = Resultset.getint (1);
        String name = resultset.getstring (2);
        int age = Resultset.getint (3);
        System.out
            . println ("id=" + ID +, name= "+ name +", age= "+ age);
      }

      Resultset.close ();
      Dbhelper.close ();
    } catch (Exception e) {
      e.printstacktrace ();}}}

The above JDBC steps and simple implementation of the code is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.

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.