JAVA-JDBC

public class JDBCTest {  
    /** 
     * 使用JDBC連接并操作mysql數(shù)據(jù)庫(kù) 
     */  
    public static void main(String[] args) {  
        // 數(shù)據(jù)庫(kù)驅(qū)動(dòng)類(lèi)名的字符串  
        String driver = "com.mysql.jdbc.Driver";  
        // 數(shù)據(jù)庫(kù)連接串  
        String url = "jdbc:mysql://127.0.0.1:3306/test";  
        // 用戶(hù)名  
        String username = "root";  
        // 密碼  
        String password = "1234";  
        Connection conn = null;  
        Statement stmt = null;  
        ResultSet rs = null;  
        try {  
            // 1、加載數(shù)據(jù)庫(kù)驅(qū)動(dòng)( 成功加載后,會(huì)將Driver類(lèi)的實(shí)例注冊(cè)到DriverManager類(lèi)中)  
            Class.forName(driver );  
            // 2、獲取數(shù)據(jù)庫(kù)連接  
            conn = DriverManager.getConnection(url, username, password);  
            // 3、獲取數(shù)據(jù)庫(kù)操作對(duì)象  
            stmt = conn.createStatement();  
            // 4、定義操作的SQL語(yǔ)句  
            String sql = "select * from user where id = 100";  
            // 5、執(zhí)行數(shù)據(jù)庫(kù)操作  
            rs = stmt.executeQuery(sql);  
            // 6、獲取并操作結(jié)果集  
            while (rs.next()) {  
                System.out.println(rs.getInt("id"));  
                System.out.println(rs.getString("name"));  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            // 7、關(guān)閉對(duì)象,回收數(shù)據(jù)庫(kù)資源  
            if (rs != null) { //關(guān)閉結(jié)果集對(duì)象  
                try {  
                    rs.close();  
                } catch (SQLException e) {  
                    e.printStackTrace();  
                }  
            }  
            if (stmt != null) { // 關(guān)閉數(shù)據(jù)庫(kù)操作對(duì)象  
                try {  
                    stmt.close();  
                } catch (SQLException e) {  
                    e.printStackTrace();  
                }  
            }  
            if (conn != null) { // 關(guān)閉數(shù)據(jù)庫(kù)連接對(duì)象  
                try {  
                    if (!conn.isClosed()) {  
                        conn.close();  
                    }  
                } catch (SQLException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
}  

這是一個(gè)jdbc的簡(jiǎn)單代碼。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容