jdbc

jdbc連接數據庫

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

jdbc連接數據庫步驟

1選擇數據庫類型和導入JAR包;2加載驅動(Class.forName("com.mysql.jdbc.Driver"));3獲取數據庫連接(DriverManager.getConnection(url, user, password););

4創建Statement對象;5調用statement執行相應的SQL;6關閉數據庫連接。

-----------------------------------------------------------------------bd連接-------------------------------------------------------------------------------------

public class Dbhelper {
    String url="jdbc:mysql://localhost:3306/test";
    String password="pwd123qwer";
    String user ="root";
    private static Connection con=null;
    public ResultSet rs = null;
    public PreparedStatement pst = null;    
    public Dbhelper(String sql){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }        
    }
    public void close(){
        try {
            this.con.close();
            this.pst.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

--------------------------------------------------------------------------------------測試連接--------------------------------------------------------------------------------------------------------

public class TestDB {
    static String sql=null;
    static Dbhelper db = null;
    static ResultSet rs = null;
    public static void main(String[] args) {
        sql="select * from customer";
        db = new Dbhelper(sql);
        try {
            rs = db.pst.executeQuery();
            JSONObject object = new JSONObject();
            object.put("rs", rs);
            System.out.println(object.get(rs).toString());            
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章