JDBC编程步骤

本文介绍了JDBC编程的基础步骤,包括使用DriverManager获取连接,执行SQL查询,以及预编译语句提高效率。展示了如何通过JDBC操作MySQL数据库并演示了预编译PreparedStatement的应用。
摘要由CSDN通过智能技术生成

JDBC的编程步骤

public class TestJDBC {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {

        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获得数据库连接
        Connection conn = DriverManager.getConnection(url, username, password);
        //向数据库发送sql的对象statement:CRUD
        Statement statement = conn.createStatement();
        //编写sql
        String sql = "select * from people";
        //执行sql语句,得到一个结果集ResultSet
        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"));
        }
        //关闭连接,释放资源,一定要关,先开后关
        rs.close();
        statement.close();
        conn.close();



    }


}

JDBC预编译

public class TestJDBC2 {
    public static void main(String[] args) throws Exception {

        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获得数据库连接
        Connection conn = DriverManager.getConnection(url, username, password);
        //编写sql
        String sql = "insert into people(id,username,password,email,birthday) values(?,?,?,?,?)";
        //预编译
        PreparedStatement preparedStatement = conn.prepareStatement(sql);

        preparedStatement.setInt(1,4);//给第一个占位符赋值
        preparedStatement.setString(2,"cdw");
        preparedStatement.setString(3,"4564");
        preparedStatement.setString(4,"456@qq.com");
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));

        //执行sql
        int i = preparedStatement.executeUpdate(sql);
        if (i>0){
            System.out.println("插入成功!");
        }

        //关闭连接,释放资源,一定要关,先开后关
        preparedStatement.close();
        conn.close();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值