JDBC数据库基本操作

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();
}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值