JDBC連接數(shù)據(jù)庫

public class TestJDBC {
    public static void main(String[] args) {
        //數(shù)據(jù)庫連接
        Connection connection = null;
        //預(yù)編譯的Statement,使用預(yù)編譯的Statement提高數(shù)據(jù)庫性能
        PreparedStatement preparedStatement = null;
        //結(jié)果集
        ResultSet resultSet = null;

        try {
            //加載數(shù)據(jù)庫驅(qū)動(dòng)
            Class.forName("com.mysql.jdbc.Driver");

            //通過驅(qū)動(dòng)管理類獲取數(shù)據(jù)庫鏈接
            connection =  DriverManager.getConnection("jdbc:mysql://172.31.50.116:3306/test_ssm?characterEncoding=utf-8", "root", "123456");
            //定義sql語句 ?表示占位符
            String sql = "select * from _user where user_name = ?";
            //獲取預(yù)處理statement
            preparedStatement = connection.prepareStatement(sql);
            //設(shè)置參數(shù),第一個(gè)參數(shù)為sql語句中參數(shù)的序號(hào)(從1開始),第二個(gè)參數(shù)為設(shè)置的參數(shù)值
            preparedStatement.setString(1, "阿堅(jiān)");
            //向數(shù)據(jù)庫發(fā)出sql執(zhí)行查詢,查詢出結(jié)果集
            resultSet =  preparedStatement.executeQuery();
            //遍歷查詢結(jié)果集
            while(resultSet.next()){
                System.out.println(resultSet.getString("user_id")+"  "+resultSet.getString("user_name"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //釋放資源
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(preparedStatement!=null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

    }
}
最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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