//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获得连接
Connection connection = DriverManger.getConnection("jdbc:mysql:///test,"root","root");
//获得statement
PreparedStatement statement = connection.prepareStatement("select * from user");
//执行查询
ResultSet resultSet = statement.executeQuery();
//遍历结果集
while(resultSet.next()){
//封装实体
User user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.serPassword(resultSet.getString("password"));
//user实体封装完毕
System.out.printLn(user);
}
//释放资源
resultSet.close();
statement.close();
connection.close();
//模拟实体对象
User user = new User();
user.setId(2);
user.setUsername("tom");
user,setPassword("123");
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获得连接
Connection connection = DriverManager.getConnection("jdbc:mysql:///test","root","root");
//获得statement
PreparedStatement statement = connection.prepareStatement("insert into user(id,username,password)values(?,?,?)");
//设置占位符参数
statement.setInt(1,user.getId());
statement.setString(2,user.getUsername());
statement.setString(3,user.getPassword());
//执行更新操作
statement.executeUpdate();
//释放资源
statement.close();
connection.close();
原文:https://www.cnblogs.com/ppvir/p/11432604.html