JDBC基础篇(MYSQL)——使用statement执行DML语句(insert/update/delete)
注意:其中的JdbcUtil是我自定义的连接工具类:代码例子链接:
package day02_statement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import util.JdbcUtil;
/**
* 使用Statement对象执行DML语句(insert/update/delete)
* @author mzy
*
*/
public class Demo03 {
public static void main(String[] args) {
// createTable();
// insertIntoTable();
// deleteFromTable();
// updateFromTable();
}
private static void deleteFromTable() {
Connection conn = null;
Statement stmt = null;
// String id = "1";
Object id = 1; // 从这里我们可以看出传入的类型会被转换不会造成影响
// 猜测是有一个instanceof
try {
// 1) 获取连接
conn = JdbcUtil.getConnection();
// 准备sql
String sql = "update employee set age = 80 where id="+id+"";
// 创建statement对象
stmt = conn.createStatement();
int count = stmt.executeUpdate(sql);
System.out.println(""+count+"行被影响了!");
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(stmt, conn);
}
}
private static void insertIntoTable() {
Connection conn = null;
Statement stmt = null;
try {
// 1) 获取连接
conn = JdbcUtil.getConnection();
// 准备sql
String sql = "INSERT INTO employee(NAME, gender, age, title, email, phone) VALUES"+
"('张三', '男', 20, '软件工程师', '123@qq.com', '12345'),"+
"('李四', '男', 30, '前端工程师', '456@qq.com', '12345'),"+
"('王五', '男', 40, '测试工程师', '789@qq.com', '12345'),"+
"('陈六', '男', 50, '数据库工程师', '123@qq.com', '12345')";
// 创建statement对象
stmt = conn.createStatement();
int count = stmt.executeUpdate(sql);
System.out.println(""+count+"行被影响了!");
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(stmt, conn);
}
}
private static void createTable() {
Connection conn = null;
Statement stmt = null;
try {
// 1) 获取连接
conn = JdbcUtil.getConnection();
// 准备sql
String sql = "CREATE TABLE employee("+
"id INT PRIMARY KEY AUTO_INCREMENT,"+
"NAME VARCHAR(20),"+
"gender VARCHAR(2),"+
"age INT,"+
"title VARCHAR(20),"+
"email VARCHAR(50),"+
"phone VARCHAR(11)"+
")";
// 创建statement对象
stmt = conn.createStatement();
int count = stmt.executeUpdate(sql);
System.out.println(""+count+"行被影响了!");
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(stmt, conn);
}
}
}