jdbc操作数据库

2018-07-19  本文已影响0人  3d7be2e0434d

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()方法

上一篇下一篇

猜你喜欢

热点阅读