当前位置:Gxlcms > 数据库问题 > JDBC 的基本步骤

JDBC 的基本步骤

时间:2021-07-01 10:21:17 帮助过:4人阅读

一、导入mysql-connector-java-x.x.x-bin.jar后:

二、代码

1. 注册驱动(三种方式)
2. 创建一个连接对象(三种方式)
3. 创建一个sql语句的发送命令对象
4. 执行SQL,拿到查询的结果集对象
5. 输出结果集的数据
6. 关闭连接,命令对象,结果集

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestJDBC {

    public static void main(String[] args) {
        //1. 注册驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        
        Connection conn = null;
        ResultSet set = null;
        try {
            
            //2. 创建一个连接对象
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","123456");
       //第一个参数是url,第二个是mysql用户名,第三个是密码。
//3. 创建一个sql语句的发送命令对象 Statement statement = conn.createStatement(); //4. 执行SQL,拿到查询的结果集对象 set = statement.executeQuery("select * from stu"); //5. 输出结果集的数据 while(set.next()){ System.out.println(set.getInt("sid") + " " + set.getString("sname")); } } catch (SQLException e) { e.printStackTrace(); }finally{ //6. 关闭连接,命令对象,结果集 if(set!=null){ try { set.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }

 

JDBC 的基本步骤

标签:

人气教程排行