?? binarydata.java
字號(hào):
package book.database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 存取二進(jìn)制數(shù)據(jù)到數(shù)據(jù)庫
*/
public class BinaryData {
/**
* 寫二進(jìn)制數(shù)據(jù)到數(shù)據(jù)庫
* @param con
*/
public static void writeBinary(Connection con){
String sql = "INSERT INTO student_address (name, address)"
+ " VALUES('john', ?)";
PreparedStatement psm = null;
try {
// 創(chuàng)建一個(gè)Statement,插入記錄到數(shù)據(jù)庫
psm = con.prepareStatement(sql);
// 創(chuàng)建要寫入的二進(jìn)制數(shù)據(jù)
byte[] buffer = "Haidian district Beijing China.".getBytes();
// 設(shè)置SQL中?的值
psm.setBytes(1, buffer);
// 插入
psm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
OperateDB.closeStatement(psm);
}
}
/**
* 從數(shù)據(jù)庫中讀二進(jìn)制數(shù)據(jù)
* @param con
*/
public static void readBinary(Connection con){
String sql = "SELECT * FROM student_address where name = 'john'";
Statement sm = null;
try {
// 查詢數(shù)據(jù)庫
Statement stmt = con.createStatement();
ResultSet resultSet = stmt.executeQuery(sql);
while (resultSet.next()) {
// 取值
byte[] bytes = resultSet.getBytes("address");
System.out.println(new String(bytes));
}
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
OperateDB.closeStatement(sm);
}
}
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
String dbName = "studentdb";
String userName = "test";
String password = "test";
Connection con = null;
try {
// 獲得數(shù)據(jù)庫連接
con = DBConnector.getMySQLConnection(null, null, null, dbName,
userName, password);
// 寫二進(jìn)制數(shù)據(jù)
BinaryData.writeBinary(con);
// 讀二進(jìn)制數(shù)據(jù)
BinaryData.readBinary(con);
} catch (ClassNotFoundException e1) {
throw e1;
} catch (SQLException e2) {
throw e2;
} finally {
// 關(guān)閉數(shù)據(jù)庫連接
OperateDB.closeConnection(con);
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -