JDBC的簡單使用——MySQL

個人博客:haichenyi.com。感謝關(guān)注

??前面幾篇學(xué)了基本的SQL語句和用工具操作數(shù)據(jù)庫,今天講一下用代碼操作數(shù)據(jù)庫。

連接MySQL

??首先記得需要導(dǎo)包,jdbc連接MySQL數(shù)據(jù)庫的jar包,名字:mysql-connector-java

??首先記得需要導(dǎo)包,jdbc連接MySQL數(shù)據(jù)庫的jar包,名字:mysql-connector-java

??首先記得需要導(dǎo)包,jdbc連接MySQL數(shù)據(jù)庫的jar包,名字:mysql-connector-java

代碼如下:

//1、獲取驅(qū)動類,路動類路徑:com.mysql.jdbc.Driver
Class.forName("com.mysql.jdbc.Driver");
//獲取url:jdbc:mysql://ip:端口號/數(shù)據(jù)庫名稱
String url = "jdbc:mysql://localhost:3306/test4";
//用戶名
String username = "root";
//密碼
String password = "123";
//獲取Connection對象
Connection connection = DriverManager.getConnection(url, username, password);
System.out.print(connection);

??總的來說,先要獲取驅(qū)動類,然后就是獲取Connection對象,就是一行代碼DriverManager.getConnection(url, username, password);能走通,就說明連接上了。

修改數(shù)據(jù)庫

@Test
    public void test1() throws ClassNotFoundException, SQLException {
        //獲取驅(qū)動類
        Class.forName("com.mysql.jdbc.Driver");
        //獲取url
        String url = "jdbc:mysql://localhost:3306/test4";
        //用戶名
        String username = "root";
        //密碼
        String password = "123";
        //獲取Connection對象
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.print(connection);
        //獲取Statement對象
        Statement statement = connection.createStatement();
        //String sql="INSERT INTO employee (eid,ename,edid) VALUES(null,'小紅',2)";
        String sql = "UPDATE employee SET edid=1 WHERE ename='小紅'";
        statement.executeUpdate(sql);
        statement.close();
        connection.close();
    }        

??就是在連接數(shù)據(jù)庫之后,通過Connection對象獲取Statement對象,通過Statement對象的execute方法執(zhí)行對應(yīng)的SQL語句,最后記得關(guān)閉

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

@Test
    public void test3() {
        Connection con = null;
        Statement state = null;
        ResultSet resultSet = null;
        try {
            String driverClassName = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/test4";
            String username = "root";
            String password = "123";
            Class.forName(driverClassName);
            con = DriverManager.getConnection(url, username, password);
            state = con.createStatement();
            String querySQL = "SELECT * FROM employee";
            resultSet = state.executeQuery(querySQL);
            List<Map<String, String>> mapList = new ArrayList<>();
            while (resultSet.next()) {
                Map<String, String> map = new HashMap<>();
                map.put("ename", resultSet.getString("ename"));
                map.put("edid", String.valueOf(resultSet.getInt("edid")));
                mapList.add(map);
            }
            System.out.print(mapList.size());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (state != null) {
                    state.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

??查詢數(shù)據(jù)庫需要注意的地方就是:

  1. 執(zhí)行SQL語句的方法是executeQuery(),只能執(zhí)行查詢語句。

  2. 他有一個返回值ResultSet,然后循環(huán)這個Set對象,獲取數(shù)據(jù),他提供了一個移動光標(biāo)的方法next(),當(dāng)他為null的時候,返回false,結(jié)束循環(huán)。

  3. 還提供了一系列的get方法,傳表每一欄的下標(biāo)index,或者每一欄的名稱,獲取對應(yīng)的值。值的類型要與get的類型相同。值為int,就用getInt,值為String就用getString

  4. 最后記得關(guān)閉連接,倒著關(guān)閉。

PreparedStatement

??上面用自己拼接sql語句的方式查詢數(shù)據(jù)庫,會容易被sql攻擊。所以,我們需要用PreparedStatement來防止被sql攻擊,具體方式如下:

public boolean login(String username, String password) throws Exception {
        Connection connection = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/test4";
            String user = "root";
            String psw = "123";
            connection = DriverManager.getConnection(url, user, psw);
            String sql = "select * from t_user where username=? and psw=?";
            pstat = connection.prepareStatement(sql);
            pstat.setString(1, username);
            pstat.setString(2, password);
            rs = pstat.executeQuery();
            return rs.next();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (rs != null) rs.close();
            if (pstat != null) pstat.close();
            if (connection != null) connection.close();
        }
    }

??如上,是一個登錄接口,傳用戶名,密碼給后臺,后臺查詢數(shù)據(jù)庫,我們在獲取了connection之后,通過connection調(diào)用prepareStatement方法,需要傳一個sql模板。

String sql = "select * from t_user where username=? and psw=?";

??什么是sql模板呢?就是吧需要動態(tài)傳的參數(shù)用問好代替。我們上面這個查詢語句,需要動態(tài)變化的就是username和psw。然后,我們調(diào)用PreparedStatement的setXxx方法,去設(shè)置值,第一個參數(shù)表示給第幾個值賦值,第二個參數(shù)就是需要賦值的值

//給第一個參數(shù)賦值為username
pstat.setString(1, username);
//給第二個參數(shù)賦值為password
pstat.setString(2, password);

大數(shù)據(jù)存儲

??這里以存mp3為例

CREATE TABLE t_binary(
    id INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAR(50),
    DATA MEDIUMBLOB
)

??如上,首先創(chuàng)建一張表去存數(shù)據(jù),數(shù)據(jù)類型不要錯了,BLOB類型。

@Test
    public void test1() throws SQLException, IOException {
        Connection connection = JDBCUtils.getConnection();
        String sql="INSERT INTO t_binary VALUE(?,?,?)";
        PreparedStatement pstat = connection.prepareStatement(sql);
        pstat.setInt(1,1);
        pstat.setString(2,"KenT - 唱給誰聽.mp3");
        byte[] bytes= IOUtils.toByteArray(new FileInputStream("D:/CloudMusic/KenT - 唱給誰聽.mp3"));
        Blob blob=new SerialBlob(bytes);
        pstat.setBlob(3,blob);
        pstat.executeLargeUpdate();
    }

??上面test1就是存的方法,步驟:

  1. 先連接數(shù)據(jù)庫,獲取Connection對象

  2. 然后,獲取PreparedStatement對象,設(shè)置參數(shù),其中blob參數(shù),Blob是一個接口,先獲取他的實(shí)現(xiàn)類SerialBlob,這個實(shí)現(xiàn)類的構(gòu)造方法需要傳一個byte[]數(shù)組,所以,我們只用把需要存儲的文件轉(zhuǎn)成byte[]數(shù)組就可以了

  3. 最后,執(zhí)行sql語句就可以了

這里需要注意的是,要在my.ini服務(wù)器配置文件中設(shè)置最大存儲

//這個大小大于你的存儲文件即可
max_allowed_packet=20M

??[mysqld]下邊的是服務(wù)器配置,[mysql]下邊的是客戶端配置

??接下來就是怎么取文件了

@Test
    public void test2() throws SQLException, IOException {
        Connection connection = JDBCUtils.getConnection();
        String sql="SELECT * FROM t_binary WHERE name=?";
        PreparedStatement pstat = connection.prepareStatement(sql);
        pstat.setString(1,"KenT - 唱給誰聽.mp3");
        ResultSet rs = pstat.executeQuery();
        if (rs.next()){
            Blob blob = rs.getBlob("data");
            InputStream in = blob.getBinaryStream();
            FileOutputStream out = new FileOutputStream("D:/cgst.mp3");
            IOUtils.copy(in,out);
        }
    }

??需要說的就是獲取到ResultSet之后,獲取到Blob,通過他的getBinaryStream()方法,轉(zhuǎn)成輸入流,拿到輸入流之后,轉(zhuǎn)成File即可

批處理

@Test
    public void test6() throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        String sql = "INSERT INTO t_user VALUE(?,?,?)";
        PreparedStatement pstat = connection.prepareStatement(sql);
        for (int i = 0; i < 10000; i++) {
            pstat.setInt(1, i + 1);
            pstat.setString(2, "user" + i);
            pstat.setString(3, i % 2 == 0 ? "男" : "女");
            pstat.addBatch();
        }
        long start = System.currentTimeMillis();
        pstat.executeBatch();
        long end = System.currentTimeMillis();
        System.out.print(end - start);
    }

??注意點(diǎn):

  1. 每添加一條數(shù)據(jù),調(diào)用一遍pstat.addBatch();
  2. 當(dāng)數(shù)據(jù)添加完以后,調(diào)用pstat.executeBatch();執(zhí)行sql語句
  3. mysql要開啟批處理功能,不然慢到你無法想象。在獲取Connection傳的url后面,添加rewriteBatchedStatements=true。完整urljdbc:mysql://localhost:3306/test4?rewriteBatchedStatements=true
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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