jdbc连接mysql,并实现删除与更新
package com.examples.jdbc.o2_删除与更新;
import java.sql.*;
//连接与插入
/*
jdbc删除操作
*/
public class Test {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
//1. 注册驱动
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
//2. 获取数据库连接对象
String url = "jdbc:mysql://ip:3306/数据库名";
String userName = "XXXX";
String passWord = "XXXX";
connection = DriverManager.getConnection(url, userName, passWord);
//3. 获取数据库操作对象
statement = connection.createStatement();
//4. 执行sql语句
//String sql = "delete from student where id=4";
String sql = "update student set sname = '郭郭' where sname = '小涵'";
int num = statement.executeUpdate(sql);
//System.out.println(num == 0? "删除失败" : "删除成功");
System.out.println(num == 0? "修改失败" : "修改成功");
//5. 查询结果集
} catch (SQLException e) {
e.printStackTrace();
}finally {
//6. 关闭资源
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
相关文章
暂无评论...