這裏列出最基本的增刪改查操作:
import Conn.Conn; //連接類我已經寫好了,直接導入 見:http://blog.csdn.net/wangzhuo0978/article/details/53019688
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Operation {
private Connection conn;
private PreparedStatement pstm = null; //預編譯結果;
// 增刪改查;
public void ConnectSQL(){
try{
conn = Conn.getConnection();
}catch(Exception e){
System.out.println("連接失敗");
}
}
public boolean insertSQL(String sql, String... ob){ // sql爲傳入的基本sql語句, pstm.setObject(), 動態修改參數;
try{
pstm = conn.prepareStatement(sql);
for(int i = 0; i < ob.length; ++i){
pstm.setObject(i+1, ob[i]);
}
int num = pstm.executeUpdate();
System.out.println("插入數據成功, 成功插入" + num + "數據");
return true;
}catch (Exception e){
System.out.println("插入數據時出錯");
}
return false;
public boolean deleteSQL(String sql){
try{
pstm = conn.prepareStatement(sql);
int num = pstm.executeUpdate();
System.out.println("刪除數據成功, 成功刪除" + num + "數據");
return true;
}catch(Exception e){
System.out.println("刪除數據時出錯");
}
return false;
}
public boolean updateSQL(String sql){
try{
pstm = conn.prepareStatement(sql);
int num = pstm.executeUpdate();
System.out.println("修改數據成功, 成功修改" + num + "數據");
return true;
}catch(Exception e){
System.out.println("修改數據時出錯");
}
return false;
}
public ResultSet selectSQL(String sql){
ResultSet rs = null;
try{
pstm = conn.prepareStatement(sql);
rs = pstm.executeQuery();
}catch(Exception e){
System.out.println("查詢數據時出錯");
}
return rs;
}
}