Create a jdbc connection

This paper introduces how to establish a jdbc connection for database query. Create a java project and import the jar package. Using mysql database, t...

This paper introduces how to establish a jdbc connection for database query.

Create a java project and import the jar package.

Using mysql database, the author needs mysql database driver jar package and jdbc connection jar package to establish jdbc connection.

The process of establishing a jdbc connection is as follows:

1. Load database driver

2. Create and obtain database connection

3. Create JDBC statement object

4. Set sql statement

5. Set parameters in sql statement

6. Execute sql through statement and get the result

7. Parse the sql execution results

8. Release resources

1 package com.xyfer; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 9 public class JdbcTest { 10 11 public static void main(String[] args) { 12 13 Connection connection = null; 14 PreparedStatement preparedStatement = null; 15 ResultSet resultSet = null; 16 17 try { 18 //Load database driver 19 Class.forName("com.mysql.jdbc.Driver"); 20 21 //Get database link through driver management class 22 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "root"); 23 //Definition sql Sentence ?Represents a placeholder 24 String sql = "select * from user where username = ?"; 25 //Get preprocessing statement 26 preparedStatement = connection.prepareStatement(sql); 27 //Set the parameter, the first parameter is sql The sequence number of the parameter in the statement (starting from 1), and the second parameter is the set parameter value 28 preparedStatement.setString(1, "Small black"); 29 //Issue to database sql Execute query to find result set 30 resultSet = preparedStatement.executeQuery(); 31 //Traverse query result set 32 while(resultSet.next()){ 33 System.out.println(resultSet.getString("id")+" "+resultSet.getString("username")); 34 } 35 } catch (Exception e) { 36 e.printStackTrace(); 37 }finally{ 38 //Release resources 39 if(resultSet!=null){ 40 try { 41 resultSet.close(); 42 } catch (SQLException e) { 43 // TODO Auto-generated catch block 44 e.printStackTrace(); 45 } 46 } 47 if(preparedStatement!=null){ 48 try { 49 preparedStatement.close(); 50 } catch (SQLException e) { 51 // TODO Auto-generated catch block 52 e.printStackTrace(); 53 } 54 } 55 if(connection!=null){ 56 try { 57 connection.close(); 58 } catch (SQLException e) { 59 // TODO Auto-generated catch block 60 e.printStackTrace(); 61 } 62 } 63 } 64 } 65 66 }

7 December 2019, 02:08 | Views: 6129

Add new comment

For adding a comment, please log in
or create account

0 comments