JDBC增刪改查
1.案例需求:jdbc增刪改查
2.需要注意的:a.優化了註冊驅動的步驟:
//1.註冊驅動com.mysql.jdbc.Driver
DriverManager.registerDriver(new Driver());
缺點:1.造成驅動被註冊了兩次
2.是程序和驅動產生了緊耦合
解決方法:Class.forName(“com.mysql.jdbc.Driver”);
b.傳輸器對象Statement
作用:用來執行SQL
提供的常用方法:
executeQuery —執行查詢的SQL
executeUpdate — 執行增刪改的SQL,返回int 類型
package on.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
/**
* 這個類用做jdbc的增刪改查操作
*
* @date 2018年3月23日
*
*/
public class JDBCCURD {
Connection conn=null;
Statement st=null;
//需求:向account中插入一條記錄
//name爲xiongda,money爲2000
@Test
public void add(){
try {
//1.註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2.獲取數據庫連接java.sql.Connection
conn=DriverManager.getConnection("jdbc:mysql:///jt_db","root","root");
//3.獲取傳輸器java.sql.Statement
st=conn.createStatement();
String sql="insert into account values( null,'xiongda','2000')";
//4.執行SQL語句
int rows=st.executeUpdate(sql);//返回一個int
//5.獲取結果集
System.out.println(rows);
} catch (Exception e) {
e.printStackTrace();
}finally{
//6.關閉資源
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn=null;
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//需求:修改account表中
//id爲3的money爲1000
@Test
public void update(){
Connection conn=null;
Statement st=null;
try {
//1.註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2.獲取數據庫連接
conn=DriverManager.getConnection("jdbc:mysql:///jt_db","root","root");
//3.獲取傳輸器
st = conn.createStatement();//快捷鍵 Ctrl+1;
//4.執行SQL
String sql="update account set money=1000 where id=3";
int rows=st.executeUpdate(sql);//返回一個int
//5.獲取查詢結果集
System.out.println(rows);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//6.關閉資源
if(conn!=null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}finally{
conn=null;
}
}
if(st!=null){
try{
st.close();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//需求:
//刪除account表中id爲3的數據
@Test
public void delete(){
Connection conn=null;
Statement st=null;
try {
//1.註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2.獲取數據庫的連接
conn=DriverManager.getConnection("jdbc:mysql:///jt_db","root","root");
//3.獲取傳輸器
st = conn.createStatement();
String sql="delete from account where id=3";
//4.執行SQL
int rows=st.executeUpdate(sql);
//5.獲取查詢結果集
System.out.println(rows);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//6.關閉資源
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn=null;
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
st=null;
}
}
}
}
}