Home > Java > javaTutorial > Detailed explanation and examples of JDBC connection to database and steps in java

Detailed explanation and examples of JDBC connection to database and steps in java

高洛峰
Release: 2017-02-28 15:37:14
Original
1909 people have browsed it

Detailed explanation of JDBC database connection code and steps in java

JDBC connection database

•Create a program to connect to the database with JDBC, including 7 steps:

1. Load the JDBC driver:

Before connecting to the database, you must first load the driver of the database you want to connect to. To the JVM (Java Virtual Machine), this is achieved through the static method forName(String className) of the java.lang.Class class.

For example:


##

  try{  
  //加载MySql的驱动类  
  Class.forName("com.mysql.jdbc.Driver") ;  
  }catch(ClassNotFoundException e){  
  System.out.println("找不到驱动程序类 ,加载驱动失败!");  
  e.printStackTrace() ;  
  }
Copy after login


After successful loading, an instance of the Driver class will be registered into the DriverManager class.​


2. Provide the URL of the JDBC connection ​

• The connection URL defines the protocol, sub-protocol, and data source identification when connecting to the database.

•Writing form: Protocol: Subprotocol: Data source identifier

Protocol: Always starts with jdbc in JDBC

Subprotocol: It is the driver or bridge connection Is the name of the database management system.​


​ Data source identification: Mark the address and connection port where the database source is found.


For example: (MySql connection URL)



 jdbc:mysql:  
    //localhost:3306/test?useUnicode=true&characterEncoding=gbk ;
Copy after login


useUnicode=true: means Use 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 database connection

•To connect to the database, you need to request and obtain the Connection object from java.sql.DriverManager. This object It represents a database connection.

•Use DriverManager's getConnectin(String url, String username, String password) method to pass in the path to the specified database to be connected, the username of the database and the password

to obtain it.


For example:



//连接MySql数据库,用户名和密码都是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("数据库连接失败!");  
  se.printStackTrace() ;  
   }
Copy after login


## 4. Create a Statement


•To execute a SQL statement, you must obtain a java.sql.Statement instance. Statement instances are divided into the following 3 types:


1. Execute static SQL statements. Usually implemented through Statement instances.​

​ 2. Execute dynamic SQL statements. Usually implemented through a PreparedStatement instance.​

​ 3. Execute the database stored procedure. Usually implemented through a CallableStatement instance.


Specific implementation method:                                                                                                                                         

The Statement interface provides three methods for executing SQL statements: executeQuery, executeUpdate and execute


1. ResultSet executeQuery(String sqlString): Execute 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, etc.

3. execute(sqlString): used to execute Statement that returns multiple result sets, multiple update counts, or a combination of both.

Specific implementation code:


Statement stmt = con.createStatement() ;  
    PreparedStatement pstmt = con.prepareStatement(sql) ;  
    CallableStatement cstmt =  
              con.prepareCall("{CALL demoSp(? , ?)}") ;
Copy after login




## 6. Processing results

Two situations:

1. Executing an update returns the number of records affected by this operation.​
2. The result returned by executing the query is a ResultSet object.


• ResultSet contains all rows that match the conditions in the SQL statement, and it provides access to the data in these rows through a set of get methods.

• Use the access method of the ResultSet object to obtain data:


     ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;  
  int rows = stmt.executeUpdate("INSERT INTO ...") ;  
  boolean flag = stmt.execute(String sql) ;
Copy after login


(Columns are numbered from left to right , and starting from column 1)


7、关闭JDBC对象

操作完成以后要把所有使用的JDBC对象全都关闭,以释放JDBC资源,关闭顺序和声 明顺序相反:

1、关闭记录集
2、关闭声明
3、关闭连接对象


     if(rs != null){  // 关闭记录集  
    try{  
      rs.close() ;  
    }catch(SQLException e){  
      e.printStackTrace() ;  
    }  
     }  
     if(stmt != null){  // 关闭声明  
    try{  
      stmt.close() ;  
    }catch(SQLException e){  
      e.printStackTrace() ;  
    }  
     }  
     if(conn != null){ // 关闭连接对象  
     try{  
      conn.close() ;  
     }catch(SQLException e){  
      e.printStackTrace() ;  
     }  
     }
Copy after login


感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

更多java 中JDBC连接数据库和步骤详解及实例相关文章请关注PHP中文网!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template