1. 首先导包,放在src -> lib下
打开项目结构,添加导入的包为库
基础语法
Statement statement = conn.createStatement();
----------------------------------------------
1.execute(String query)方法用来执行任意的SQL语句查询,如果查询的结果是一个ResultSet,这个方法就返回true,
如果结果不是ResultSet,比如:insert或update,就会返回false.可以通过getResultSet方法来获取ResultSet。
2.executeQuery(String query)接口用来执行select查询,并返回ResultSet,
即便查询不到记录,返回的ResultSet也不会为null.
3.executeUpdate(String query)方法用来执行insert,delete或者update语句,返回值是int类型,
如果是DML语句,则是更新的条数,如果是DDL,则返回0
普通使用
private String connStr = "jdbc:mysql://localhost:3306/red1";
private String user = "root";
private String pwd = "123456";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(connStr, user, pwd);
Statement statement = conn.createStatement();
String sql="select * from table";
statement.execute(sql);
statement.close();
conn.close();
新增
public void addKeShi(String str1, String str2) throws ClassNotFoundException, SQLException {
Connection conn = DriverManager.getConnection(connStr, user, pwd);
Statement statement = conn.createStatement();
String sql = "INSERT INTO ke_shi(name,describe1) VALUES ('" + str1 + "','" + str2 + "')";
int num = statement.executeUpdate(sql);
if (num == 1) {
System.out.println("科室新增成功\n");
} else {
System.out.println("科室新增失败,SQL语句为:" + sql + "\n");
}
statement.close();
conn.close();
}
查询所有
public List<KeShi> getAllKeShi() throws ClassNotFoundException, SQLException {
Connection conn = DriverManager.getConnection(connStr, user, pwd);
Statement statement = conn.createStatement();
String sql = "SELECT * FROM ke_shi";
ResultSet rs = statement.executeQuery(sql);
List<KeShi> list = new ArrayList<>();
KeShi keShi=null;
while (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
String describe = rs.getString(3);
keShi=new KeShi(id,name,describe);
list.add(keShi);
}
statement.close();
conn.close();
return list;
}
修改
public void changeKeShiByID(int id, String str1, String str2) throws ClassNotFoundException, SQLException {
Connection conn = DriverManager.getConnection(connStr, user, pwd);
Statement statement = conn.createStatement();
String sql = "UPDATE ke_shi SET name='" + str1 + "',describe1='" + str2 + "' WHERE id = " + id;
int num = statement.executeUpdate(sql);
if (num == 1) {
System.out.println("科室修改成功\n");
} else {
System.out.println("科室修改失败,SQL语句为:" + sql + "\n");
}
statement.close();
conn.close();
}
删除
public void deleteKeShiByID(int id) throws ClassNotFoundException, SQLException {
Connection conn = DriverManager.getConnection(connStr, user, pwd);
Statement statement = conn.createStatement();
String sql = "DELETE FROM ke_shi WHERE id =" + id;
int num = statement.executeUpdate(sql);
if (num == 1) {
System.out.println("科室删除成功\n");
} else {
System.out.println("科室删除失败,SQL语句为:" + sql + "\n");
}
statement.close();
conn.close();
}