JDBC编程之数据增加,更改,查询,删除
package com.good.jdbc; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement; public class Main {
//1数据库连接的方法就独立出来了
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db","root","");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//2然后编写一个同样是静态的向数据表中插入数据的方法
public static void insert(){
//获取数据库连接
Connection conn = getConnection();
try {
String sql = "INSERT INTO tbl_user(name,password,email)" +
"VALUES('Tom','123456','tom@gmail.com')";
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向用户表中插入了 " + count + " 条记录");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//3接下来写一个更新的方法
public static void update(){
//获取数据库连接
Connection conn = getConnection();
try {
String sql = "UPDATE tbl_user SET email='tom@126.com' WHERE name = 'Tom'";
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向用户表中更新了 " + count + " 条记录");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//4删除记录的方法
public static void delete(){
//获取数据库连接
Connection conn = getConnection();
try {
String sql = "DELETE FROM tbl_user WHERE name = 'TOM'";
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向用户表中删除了 " + count + " 条记录");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// insert();
delete();
update();
}
}