第一个JDBC程序

第一个JDBC程序:

import java.sql.*;

public class jdbc {
    public static void main(String[] args)throws ClassNotFoundException, SQLException {
        //1.加载驱动;
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.用户信息和url;
        String url="jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT";
        String username="root";
        String password="123456";
        //3.连接成功,数据库对象;
        Connection connection= DriverManager.getConnection(url,username,password);
        //4.执行SQL的对象; Statement
        Statement statement=connection.createStatement();
        //5.执行SQL的对象 去执行SQL。可能存在结果,查看返回结果;
        String sql="SELECT * FROM student";
        ResultSet resultSet=statement.executeQuery(sql);
        //返回的结果集,结果集中封装了我们全部的查询出来的结果;
        while (resultSet.next()){
            System.out.println("id="+resultSet.getObject("id"));
            System.out.println("name="+resultSet.getObject("name"));
            System.out.println("pwd="+resultSet.getObject("pwd"));
            System.out.println(".....................................");
        }
        //6.释放连接;
        resultSet.close();
        statement.close();
        connection.close();
    }
}
总结步骤:
  1. 加载驱动;
  2. 连接数据库 DriverManager;
  3. 获得执行SQL的对象 Statement;
  4. 获得返回的结果集;
  5. 释放连接;
Statement执行SQL的对象 PrepareStatement执行SQL的对象
String sql="SELECT * FROM student";  //编写SQL;

statement.executeQuery();   //查询操作,返回ResultSet;
statement.execute();          //执行任何SQL;
statement.executeUpdate();    //更新,插入,删除都是用这个,返回一个受影响的行数;
posted @ 2021-04-08 22:06  Sikz  阅读(49)  评论(0)    收藏  举报