首先建立一個靜態方法,代碼如下:
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','[email protected]')";
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='[email protected]' 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();
}