下面是在day10数据库下的表user进行操作的。
如果是更改了数据那么就使用Statement 中的executeUpdate()方法。如果是查询就使用executeQuery()方法.
案例:
package cn.itheima.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
import cn.itheima.utils.JDBCUtils;
public class JDBCDemo4 {
private static Connection con=null;
private static Statement sta=null;
private static ResultSet rs=null;
@Test
public void add(){
try {
con=JDBCUtils.getConnection();
sta=con.createStatement();
sta.executeUpdate("insert into user values(3,'韩玮',0,'1996-02-01')");
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}finally{
JDBCUtils.closeResource(rs, sta, con);
}
}
@Test
public void find(){
try {
con=JDBCUtils.getConnection();
sta=con.createStatement();
rs=sta.executeQuery("select * from user where name='李卫康'");
while(rs.next()){
String name = rs.getString("name");
System.out.println(name);
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}finally{
JDBCUtils.closeResource(rs, sta, con);
}
}
@Test
public void update(){
try {
con=JDBCUtils.getConnection();
sta=con.createStatement();
sta.executeUpdate("update user set gender=0 where name='李卫康'");
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}finally{
JDBCUtils.closeResource(rs, sta, con);
}
}
@Test
public void delete(){
try {
con=JDBCUtils.getConnection();
sta=con.createStatement();
sta.executeUpdate("delete from user where name='程崇树'");
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}finally{
JDBCUtils.closeResource(rs, sta, con);
}
}
}