java操作mysql

這裏列出最基本的增刪改查操作:


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;  
    }  
}  


發佈了118 篇原創文章 · 獲贊 8 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章