
首先建立一个静态方法,代码如下:
public static Statement getStatement(){
Statement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_dbb", "root", "");
st = (Statement) conn.createStatement();
} catch (Exception e) {
// TODO: handle exception
}
return st;
}
这个静态类获取Statement,通过Statement类来实现添加,更新和删除操作,分别是静态代码实现的。全部代码如下:
public static Statement getStatement(){
Statement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_dbb", "root", "");
st = (Statement) conn.createStatement();
} catch (Exception e) {
// TODO: handle exception
}
return st;
}
public static void insert(){
try {
String sql = "INSERT INTO tbl_user(name,password,email)" +
"VALUES('Tom','123456','tom@qq.com')";
Statement st = getStatement();
int count = st.executeUpdate(sql);
System.out.println("插入了"+count+"行数据");
} catch (Exception e) {
// TODO: handle exception
}
}
public static void update(){
try {
String sql = "UPDATE tbl_user SET email='tom@136.com' WHERE name='Tom'";
Statement st = getStatement();
int count = st.executeUpdate(sql);
System.out.println("更新了"+count+"行数据");
} catch (Exception e) {
// TODO: handle exception
}
}
public static void delete(){
try {
String sql = "DELETE FROM tbl_user WHERE name='Tom'";
Statement st = getStatement();
int count = st.executeUpdate(sql);
System.out.println("删除了"+count+"行数据");
} catch (Exception e) {
//
}
}
public static void main(String[] args) {
//insert();
//update();
delete();
}