JDBC(三)數(shù)據(jù)庫(kù)連接和數(shù)據(jù)增刪改查

加載JDBC驅(qū)動(dòng)

只需要在第一次連接數(shù)據(jù)庫(kù)時(shí)加載,java6以后我們可以直接這樣加載:
*我在本系列教程中用mysql示例。

  1. 需要導(dǎo)入jar包:mysql-connector-java-5.0.8-bin.jar(版本和下載網(wǎng)站自己挑)
  2. 如果是web程序,把jar包放到WebRoot/WEB-INF/lib/下
  3. 如果是普通java項(xiàng)目,將jar包導(dǎo)入到自己項(xiàng)目的lib庫(kù)中。
  4. 然后加載驅(qū)動(dòng)如下
Class.forName("com.mysql.jdbc.Driver");

打開連接

打開連接的話需要調(diào)用DriverManager類中的getConnection()方法,該方法有三個(gè)重載方法。如下所示

public static Connection getConnection(String url,
        java.util.Properties info) throws SQLException {

        return (getConnection(url, info, Reflection.getCallerClass()));
    }

public static Connection getConnection(String url,
        String user, String password) throws SQLException {
        java.util.Properties info = new java.util.Properties();

        if (user != null) {
            info.put("user", user);
        }
        if (password != null) {
            info.put("password", password);
        }

        return (getConnection(url, info, Reflection.getCallerClass()));
}


    public static Connection getConnection(String url)
        throws SQLException {

        java.util.Properties info = new java.util.Properties();
        return (getConnection(url, info, Reflection.getCallerClass()));
    }

大概看下它的參數(shù)名字應(yīng)該知道它需要什么吧。在這里我只解釋第一個(gè)方法。Properties info 這個(gè)參數(shù)其實(shí)也是user和password的打包。其實(shí)和方法二一樣。

實(shí)例:
public class Main {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/user";
        String user = "root";
        String password = "root";

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            // 1.加載驅(qū)動(dòng)//com.mysql.jdbc.Driver
            Class.forName("com.mysql.jdbc.Driver");
            // 2.獲取連接
            connection = DriverManager.getConnection(url, user, password);

            // 3.獲取用于向數(shù)據(jù)庫(kù)發(fā)送SQL的Statement對(duì)象
            statement = connection.createStatement();

            // 4.執(zhí)行sql,獲取數(shù)據(jù)
            resultSet = statement.executeQuery("SELECT * FROM user;");

            // 解析數(shù)據(jù)
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("username");
                String psd = resultSet.getString("birthday");
                String email = resultSet.getString("sex");
                String birthday = resultSet.getString("address");

                System.out.println(" " + name + " " + psd + " " + email
                        + " " + birthday);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            //5.關(guān)閉連接,釋放資源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                resultSet = null;
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                statement = null;
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                connection = null;
            }
        }
    }
}

數(shù)據(jù)查詢

數(shù)據(jù)查詢需要我們將sql發(fā)送給數(shù)據(jù)庫(kù),我們需要?jiǎng)?chuàng)建一個(gè)Statement對(duì)象。

Statement statement = connection.createStatement();

因?yàn)镾tatement對(duì)象可以執(zhí)行sql

String sql = "select * from user";

ResultSet resultSet = statement.executeQuery(sql);

當(dāng)執(zhí)行一個(gè)sql查詢的時(shí)候,會(huì)得道一個(gè)ResultSet對(duì)象,它里面放著查詢的結(jié)果。

ResultSet resultSet = statement.executeQuery("SELECT * FROM user;");

那怎樣獲取user表中對(duì)應(yīng)列的數(shù)據(jù)呢?

    resultSet .getString    ("columnName");
    resultSet .getLong      ("columnName");
    resultSet .getInt       ("columnName");
    resultSet .getDouble    ("columnName");
    resultSet .getBigDecimal("columnName");

或者通過(guò)第幾列進(jìn)行查詢。

    resultSet .getString    (1);
    resultSet .getLong      (2);
    resultSet .getInt       (3);
    resultSet .getDouble    (4);
    resultSet .getBigDecimal(5);

如果你想知道對(duì)應(yīng)列名的index值(位于第幾列),可以這樣

 int columnIndex = resultSet .findColumn("columnName");

數(shù)據(jù)修改/刪除

為什么要把修改和刪除放一塊說(shuō)呢,因?yàn)樗麄兒筒樵冋{(diào)用不一樣的方法。
查詢我們調(diào)用executeQuery()方法,修改和刪除我們需要用executeUpdate()方法。
舉個(gè)簡(jiǎn)單的例子:

//更新數(shù)據(jù)(也叫修改數(shù)據(jù))
String    sql       = "update user set name='fantj' where id=1";

int rowsAffected    = statement.executeUpdate(sql);    //rowsAffected是影響行數(shù)的意思

//刪除數(shù)據(jù)
String    sql       = "delete from user where id=123";

int rowsAffected    = statement.executeUpdate(sql);

關(guān)閉連接

為了安全性和項(xiàng)目性能,我們盡量在執(zhí)行完操作之后關(guān)閉連接(雖然高版本jvm會(huì)自動(dòng)關(guān)閉它,但是這也需要檢測(cè)浪費(fèi)cpu資源)。
關(guān)閉連接分為三個(gè)部分。

  • resultSet.close();
  • statement.close();
  • connection.close();

注意先后問(wè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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,275評(píng)論 6 342
  • 秋漸,秋漸,立馬合目遠(yuǎn)看。關(guān)山萬(wàn)里重城,飄搖回雪流風(fēng)。 風(fēng)流,風(fēng)流,輕酌一杯綠酒。 ...
    林間狐閱讀 276評(píng)論 0 2
  • 最近我的好朋友小雅又和男朋友吵架了。自從畢業(yè)之后兩人就吵架不斷。小雅是事業(yè)心比較強(qiáng)的人,大學(xué)就比較努力,一...
    喵小鬼的Castle閱讀 809評(píng)論 1 1
  • 首先, 請(qǐng)?jiān)试S我代表各位家長(zhǎng)向辛勤培育孩子的老師們表示最誠(chéng)摯的敬意和最衷心的感謝!感謝魏老師和全體老師的關(guān)愛(ài)...
    行走的教育閱讀 312評(píng)論 0 0

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