jdbc数据库
数据库查询
try {
Class.forName(“com.mysql.jdbc.Driver”);
// 2.创建连接
Connection connection=DriverManager.getConnection(“jdbc:mysql://localhost/jdbc?user=root&password=064038”);
//3.写sql
String sql=“select * from tb_user”;
//4.得到statement对象
PreparedStatement preparedStatement=connection.prepareStatement(sql);
//5.执行sql
ResultSet resultSet=preparedStatement.executeQuery();
//6.处理结果集
while(resultSet.next()){
System.out.println(resultSet.getInt(1));
System.out.println(resultSet.getString(2));
}
//7.关闭资源
}catch (Exception e){
e.printStackTrace();
}
}
数据库添加
try {
//1.加载驱动
Class.forName(“com.mysql.jdbc.Driver”);
// 2.创建连接
Connection connection=DriverManager.getConnection(“jdbc:mysql://localhost/jdbc?user=root&password=064038”);
//3.写sql
String sql=“insert into tb_user values (11,11,11)”;
//4.得到statement对象
PreparedStatement preparedStatement=connection.prepareStatement(sql);
preparedStatement.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}
数据库删除
try {
//1.加载驱动
Class.forName(“com.mysql.jdbc.Driver”);
// 2.创建连接
Connection connection=DriverManager.getConnection(“jdbc:mysql://localhost/jdbc?user=root&password=064038”);
//3.写sql
String sql=“DELETE FROM tb_user WHERE username=‘赵六’”;
//4.得到statement对象
PreparedStatement preparedStatement=connection.prepareStatement(sql);
preparedStatement.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}
数据库更新
try {
//1.加载驱动
Class.forName(“com.mysql.jdbc.Driver”);
// 2.创建连接
Connection connection= DriverManager.getConnection(“jdbc:mysql://localhost/jdbc?user=root&password=064038”);
//3.写sql
String sql=“UPDATE tb_user SET username=‘ri’ WHERE id=5;”;
//4.得到statement对象
PreparedStatement preparedStatement=connection.prepareStatement(sql);
preparedStatement.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}
}