JDBC的增删改查
今天在讲师的耐心讲解下,我们学习了用IDEA软件进行JDBC的增删改查操作。
老师利用投屏软件先演示了JDBC的七步骤:
1.加载驱动
2.创建链接
3.写数据库
4. 得到statement对象
5. 执行数据库,得到结果集
6. 处理结果集
7.关闭资源
我们在老师的引导下尝试用IDEA进行了编程。
获取数据库的连接
public static Connection getConnection() {//创建连接
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc1?useSSL=true&characterEncoding=utf-8&user=root&password=whuthhy");
//connection=DriverManager.getConnection(url,username,password);
return connection;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
关于url的写法,url=“jdbc:mysql://127.0.0.1:3306/(+目标数据库名字+)?useSSL=true&characterEncoding=utf-8&user=(你的MySQL用户名)&password=(你的密码)”
资源关闭
public static void Close(PreparedStatement statement, Connection connection) {
//资源关闭
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
之所以将这两部分列出来是因为增删改查都要用到这两部分,可以把他们放到DBUtil包里,需要就调用,进行代码简化。
我写的增删改查语句
目标数据库jdbc1
查询
String sql="select * from yonghu";
//4.得到statement对象
statement = DBUtil.getConnection().prepareStatement(sql);
//5.执行sql 得到结果集
resultSet = statement.executeQuery();
//6.处理结果集
while(resultSet.next()){
System.out.println(resultSet.getInt(1));
System.out.println(resultSet.getString(2));
System.out.println(resultSet.getString(3));
}
运行截图
增加/插入
String sql = "insert into yonghu (username,password) values (?,?)";
statement = DBUtil.getConnection().prepareStatement(sql);
statement.setString(1, "二狗子");
statement.setString(2, "www");
int res = statement.executeUpdate();
if(res>0){
System.out.println("增加数据成功!!!");
}
运行截图
多次增加数据
删除
String sql="delete from yonghu where id>6";
statement = DBUtil.getConnection().prepareStatement(sql);
//statement.executeUpdate();
//executeUpdate 的返回值是一个整数,指示受影响的行数(即更新计数)。对于 CREATE TABLE 或 DROP TABLE 等不操作行的语句,executeUpdate 的返回值总为零。
int res = statement.executeUpdate();
if(res>0){
System.out.println("刪除数据成功!!!");
}
运行截图
更新
String sql="update yonghu set username = ?, password = ? where id = ?";
statement = DBUtil.getConnection().prepareStatement(sql);
((PreparedStatement) statement).setString(1,"tom");
((PreparedStatement) statement).setString(2,"666666");
((PreparedStatement) statement).setString(3,"1");
//((PreparedStatement) statement).executeUpdate();
int res = ((PreparedStatement) statement).executeUpdate();
if(res>0){
System.out.println("更新数据成功!!!");
}
运行截图
个人体会
本次主要是熟悉JDBC和IDEA的使用,IDEA的确很方便。还要注意的就是文件分层,还有代码简化,我还有很多地方要去改进。