Home > Java > javaTutorial > Detailed explanation of the use of jdbc in Java

Detailed explanation of the use of jdbc in Java

黄舟
Release: 2017-09-16 10:17:31
Original
1520 people have browsed it

1. Load the driver (the driver for mysql is com.mysql.jdbc.Driver, the driver for SqlServer is com.microsoft.sqlserver.jdbc.SQLServerDriver)

2. Load the database connection (url, username , password)

3. Write the sql statement (String sql="select * from grade where gradeName = ?";)

4. Traverse the query results [while (resultSet.next()) {
System.out.println(resultSet.getInt("gradeId") + " " + resultSet.getString("gradeName"));
}】

5. Close the resource (from now on Close resource forward)

public class Test {
public static void main(String[] args) {
 Connection connection = null;
 PreparedStatement preparedStatement = null;
 ResultSet resultSet = null;
 try {
  // 加载数据库驱动
  Class.forName("com.mysql.jdbc.Driver");
  // 通过驱动管理类获取数据库链接
  connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool?characterEncoding=utf-8", "root", "root");
  // 定义sql语句 ?表示占位符
  String sql = "select * from grade  where gradeName = ?";
  // 获取预处理statement
  preparedStatement = connection.prepareStatement(sql);
  // 设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
  preparedStatement.setString(1, "二年级");
  // 向数据库发出sql执行查询,查询出结果集
  resultSet = preparedStatement.executeQuery();
  // 遍历查询结果集
  while (resultSet.next()) {
   System.out.println(resultSet.getInt("gradeId") + "  " + resultSet.getString("gradeName"));
  }
 } catch (Exception e) {
  e.printStackTrace();
 } finally {
  // 释放资源
  if (resultSet != null) {
   try {
    resultSet.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  if (preparedStatement != null) {
   try {
    preparedStatement.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  if (connection != null) {
   try {
    connection.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}
}
Copy after login

The above is the detailed content of Detailed explanation of the use of jdbc in Java. For more information, please follow other related articles on the PHP Chinese website!

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