JDBC操作流程

1.需要jar包的支持:

  • java.sql
  • javax.sql
  • mysql-conneter-java...连接驱动(必须要导入)
  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
    </dependency>

2.非安全型(未使用预编译)

public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "root";

        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //3.向数据库发送SQL的对象Statement
        Statement statement = connection.createStatement();

        //4.编写SQL
        String sql = "select * from users";

        //5.查询SQL
        ResultSet rs = statement.executeQuery(sql);

        while(rs.next()){
            System.out.println("id=" + rs.getObject("id"));
            System.out.println("name=" + rs.getObject("name"));
            System.out.println("password=" + rs.getObject("password"));
            System.out.println("email=" + rs.getObject("email"));
            System.out.println("birthday=" + rs.getObject("birthday"));

        }
        //6.关闭连接,释放资源
        rs.close();
        statement.close();
        connection.close();
    }
}

3.预编译型

public class TestJDBC2 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "root";
        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //3.编写SQL
        String sql = "insert into users(id,name,password,email,birthday) values (?,?,?,?,?)";
        //4.预编译
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, 4);
        preparedStatement.setString(2, "林");
        preparedStatement.setString(3, "123456");
        preparedStatement.setString(4, "123456@qq.com");
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));
        //5.执行SQL
        int i = preparedStatement.executeUpdate();
        if(i>0){
            System.out.println("插入成功");
        }
        //6.关闭连接,释放资源
        preparedStatement.close();
        connection.close();
    }
}
posted @ 2022-08-23 12:12  林枢  阅读(33)  评论(0编辑  收藏  举报