美文网首页
jdbc操作数据库

jdbc操作数据库

作者: 3d7be2e0434d | 来源:发表于2018-07-19 19:12 被阅读0次

    1.简单不含参数的查询

    //1.加载数据库驱动

    Class.forName("com.mysql.jdbc.Driver");

    //2.创建数据库连接对象

    String url = "jdbc:mysql://localhost:3306/user";

    String username = "root";

    String password = "anogvb123";

    Connection con = DriverManager.getConnection(url, username,password);

    //3.获取Statement对象

    Statement stmt = con.createStatement();

    //4.使用statement对象执行  sql 语句

    String sql = "select * from user";

    ResultSet rs = stmt.executeQuery(sql);

    //5.操作 ResultSet结果集

    while(rs.next()){

    int id = rs.getInt("id");

    String name = rs.getString("name");

    String psw = rs.getString("password");

    String email = rs.getString("email");

    Date birthday = rs.getDate("birthday");

    System.out.println(id+" | "+name+" | " + psw +" | "+ email +" | "+birthday);

    }

    rs.close();

    stmt.close();

    con.close();

    2.含参数的插入操作

    //1.加载数据库驱动

    Class.forName("com.mysql.jdbc.Driver");

    //2.创建数据库连接对象

    String url = "jdbc:mysql://localhost:3306/user";

    String username = "root";

    String password = "anogvb123";

    Connection con = DriverManager.getConnection(url, username,password);

    String sql = "insert into user (name,password,email,birthday) values(?,?,?,?)";

    PreparedStatement preStmt = con.prepareStatement(sql);

    preStmt.setString(1, "z1");

    preStmt.setString(2, "123456");

    preStmt.setString(3, "z1.@163.com");

    preStmt.setString(4, "1789-10-23");

    preStmt.executeUpdate();

    preStmt.close();

    con.close();

    3.同样含参数的查询 也是用 preStmt,然后设置参数,最后调用executeQuery方法,最后遍历 

    4.带参数的删除操作,用preStmt,设置参数,preStmt.excut()方法

    相关文章

      网友评论

          本文标题:jdbc操作数据库

          本文链接:https://www.haomeiwen.com/subject/rpbvpftx.html