@Test
public void addJdbc(){
try {
Class.forName(driverClassName);
Connection con = DriverManager.getConnection(url, username, password);
Statement statement = con.createStatement();
statement.execute("insert into dept(id,name,location) values (100,'学术部','深圳')");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void delJdbc(){
try {
Class.forName(driverClassName);
Connection con = DriverManager.getConnection(url, username, password);
Statement statement = con.createStatement();
String sql;
sql="delete from dept where id=100";
statement.execute(sql);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void editJdbc(){
try {
Class.forName(driverClassName);
Connection con = DriverManager.getConnection(url, username, password);
Statement statement = con.createStatement();
statement.execute("update dept set location='上海' where id = 33");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
查询
@Test
public void listJdbc(){
try {
Class.forName(driverClassName);
Connection con = DriverManager.getConnection(url, username, password);
Statement statement = con.createStatement();
String sql;
sql="select * from dept";
ResultSet rs = statement.executeQuery(sql);
int id = 0;
String name = "";
String location = "";
while (rs.next()){ //处理结果集
id = rs.getInt("id");
name = rs.getString("name");
location = rs.getString("location");
System.out.println(id + " " + name + " " + location);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
或者
public void add2() throws Exception{
Class.forName(driverClassName);
Connection con = DriverManager.getConnection(url, username, password);
PreparedStatement ps = con.prepareStatement("insert into lib(id,name,price,date) values(?,?,?,?)");
ps.setInt(1,111);
ps.setString(2,"蜜汁炖鱿鱼");
ps.setDouble(3,36.9);
String date = "1999-8-8 19:52:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //转换
Date d = sdf.parse(date);
long time = d.getTime();
ps.setDate(4,new java.sql.Date(time));
int rows = ps.executeUpdate();
if (rows > 0){
System.out.println("success");
}else{
System.out.println("error");
}
简单化
public class JdbcUtil2 {
public static void main(String[] args) {
// update("insert into category (id,name) values (221,'公关部')");
// update("delete from category where i d=?");
// update("update category set name='社会' where id=77");
query("select * from category");
}