# JDBC ###### tags: `Java` `JDBC` ## 遇到的坑 ### 返回資料時遇到中文變成亂碼問題 在response要設定contentType ``` response.setContentType("application/json; charset=UTF-8"); ``` ## JDBC的動作 建立資料庫連接connection,connection做sql動作,結束記得的要closed每個動作 ## 用法範例: 執行一個sql ``` SimpleDBSource dbsource = new SimpleDBSource(); Connection conn = dbsource.getConnection(); PreparedStatement stmt = conn.prepareStatement( sql語法 ); stmt.setString(1, String); stmt.executeUpdate(); stmt.close(); conn.close(); ``` Select獲取資料並轉成JSONArray格式 ResultSet ResultSetMetaData ``` JSONObject element = null; JSONArray ja = new JSONArray(); String columnName = null; Object columnValue = null; ResultSet result = stmt.executeQuery(); ResultSetMetaData metaData = result.getMetaData(); while (result.next()) { element = new JSONObject(); for (int i = 0; i < metaData.getColumnCount(); i++) { columnName = metaData.getColumnLabel(i + 1); columnValue = result.getObject(columnName); if (columnValue == null || "".equals(columnValue)) { continue; } try { columnValue = new JSONObject((String) columnValue); } catch (Exception e) { try { columnValue = new JSONArray((String) columnValue); } catch (Exception e1) { } } element.put(columnName, columnValue); } ja.put(element); } ``` ## 返回值 統一使用PreparedStatement來操作sql,彈性較大 ### Update操作返回值 int ***JDBC Update操作DML语句默认情况下返回Rows-Matches数目,而不是Rows-Affect数目,可以在url中加入userAffectedRows=true 则会返回Rows-Affect数目*** ``` Connection connection = DriverUtils.getConnection(); String sql = "INSERT INTO update_return_value(name) VALUES (?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, "2222"); int updateValue = preparedStatement.executeUpdate(); System.out.println("Update Return Value: " + updateValue); ``` ### Insert操作返回主键 必须是Auto Increment ``` PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, "3333"); preparedStatement.executeUpdate(); ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); while (generatedKeys.next()) { long generateKey = generatedKeys.getLong(1); } ``` ## 名詞解釋: ``` DML(data manipulation language)資料操縱語言:資料庫的資料進行一些操作 SELECT、UPDATE、INSERT、DELETE DDL(data definition language)資料庫定義語言:主要是用在定義或改變表的結構,資料型別,表之間的連結和約束等初始化工作上 CREATE、ALTER、DROP DCL(Data Control Language)資料庫控制語言:用來設定或更改資料庫使用者或角色許可權的語句 grant deny revoke 很少用到 ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up