JDBC连接MySQL数据库步骤

来源:互联网 发布:sql主键和外键 编辑:程序博客网 时间:2024/05/11 03:25

JDBC
1. mysql
   ...
2. JDBC
   2.1 连接数据库步骤
       2.1.1 加入数据库驱动包(将包copy到lib下,右键 --> build path--> add to build path)
       2.1.2 加载驱动
      Class.forName("com.mysql.jdbc.Driver");
       2.1.3 建立连接

           //oa为数据库名称,root为数据库登录名,登录密码为空
           Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/oa", "root", "");
       2.1.4 创建sql执行对象
           PreparedStatement pst = connection.prepareStatement("insert into t_person values(4, '张学友', '男')");
   2.1.4.1 设置参数,若创建执行对象时,设置的参数有?,则需使用setInt来设置
              pst.setInt(1, 4);
       2.1.5 执行sql
           pst.executeUpdate();
          2.1.5.1 处理执行结果
       2.1.6 关闭连接
           connection.close();

3、设置参数详解

    PreparedStatement pst = connection.prepareStatement("insert into t_person values(?, ?, ?)");

   pst.setInt(1,person.getId());

  pst.setString(2,person.getName());

  pst.setString(3,person.getSex());