JDBC进行增删改
方法 | 描述 |
executeUpdate() | 操作DML语句 |
1.导入mysql的jar包
2.写代码,六步骤
实例代码
public class JDBCTest {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//第一步:注册驱动
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
//第二步:获取连接
String url = "jdbc:mysql://localhost:3306/lxyk";
String username = "root";
String password = "root";
conn = DriverManager.getConnection(url, username, password);
//输出连接对象的内存地址
//com.mysql.jdbc.JDBC4Connection@25f38edc
//com.mysql.jdbc.JDBC4Connection@1a86f2f1 实现了 java.sql.Connection接口
System.out.println(conn);
//第三步:获取数据库操作对象
//通过一个连接对象 Connection 是可以创建多个 Statement对象的
stmt = conn.createStatement();
System.out.println(stmt); //com.mysql.jdbc.StatementImpl@3eb07fd3
//第四步:执行SQL语句(DQL DML....)
// insert delete update
// Statement 接口中的 executeUpdate 方法专门来执行DML语句的。
// 该方法的返回值表示:影响了数据库表中的总记录条数!
//新增
/*String insertSql = "insert into dept(deptno,dname,loc)values(50,'教学部','武汉')";
int insertCount = stmt.executeUpdate(insertSql);
System.out.println(insertCount);*/
//修改
/* String updateSql = "update dept set dname = '人事部',loc = '广州' where deptno = 50";
int updateCount = stmt.executeUpdate(updateSql);
System.out.println(updateCount);*/
//删除
String deleteSql = "delete from dept where deptno = 50";
int deleteCount = stmt.executeUpdate(deleteSql);
System.out.println(deleteCount);
//第五步:处理查询结果集(只有当第四步执行的是select语句的时候,才有这第五步处理查询结果集。)
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
//第六步:释放资源
//先释放 Statement 在释放 Connection
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}