JDBC实例:执行遍历查询操作,并打印查询结果

 

//导入了Java的SQL包
import java.sql.*;

public class Main {
    public static void main(String[] args) throws Exception {
//      注册MySQL的JDBC驱动
        Class.forName("com.mysql.jdbc.Driver");
//      连接自己的数据库,我连接了数据库“pinta”
        String url = "jdbc:mysql://localhost:3306/pinta";
//      数据库用户名和密码
        String username = "root";
        String password = "123456";

//      使用上述的URL、用户名和密码建立与数据库的连接。如果连接成功,DriverManager将返回一个Connection对象。
        Connection connection = DriverManager.getConnection(url, username, password);

//      从Connection对象中获取一个Statement对象,用于执行SQL查询或更新。
        Statement statement = connection.createStatement();

//      执行SQL查询命令
        String sql = "SELECT * FROM course";
//      使用Statement对象执行SQL查询,并将结果存储在ResultSet对象中。
        ResultSet resultSet = statement.executeQuery(sql);
//      遍历查询并打印结果
        int i=0;
        while (resultSet.next()){
            i++;
            System.out.println("表中第"+i+"行数据:");
            System.out.println("cno = " + resultSet.getObject("cno"));
            System.out.println("cname = " + resultSet.getObject("cname"));
            System.out.println("cpno = " + resultSet.getObject("cpno"));
            System.out.println("ccredit = " + resultSet.getObject("ccredit")+"\n");

        }
//      关闭资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}

 

posted @ 2024-06-20 14:14  joiny-  阅读(90)  评论(0)    收藏  举报