這是我當前的字符集。我試圖插入拉丁文字符,我不能得到它的工作。mysql jdbc驅動程序不識別latin1字符
SHOW VARIABLES LIKE 'char%';
+--------------------------+-----------------------------------+
| Variable_name | Value |
+--------------------------+-----------------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /space/xyz/mysql/share/charsets/ |
+--------------------------+-----------------------------------+
數據庫配置不是由我創建的,所以我不能更改字符集或整理。
show create table t1;
+-------+-------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+-------------------------------------------------------------------------------------------------------------------------+
| t1 | CREATE TABLE `t1` (
`col1` text CHARACTER SET latin1
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_cs |
+-------+-------------------------------------------------------------------------------------------------------------------------+
以下是插入帶有unicode字符的名稱的簡單代碼。
private void insert() {
try {
loadJdbcProperties();
String myquery = "INSERT INTO db.t1(col1) VALUES (?)";
String url = "jdbc:mysql://localhost:3307/db?useUnicode=true&characterEncoding=Cp1252";
Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "root");
if (_jdbcProperties != null && !_jdbcProperties.isEmpty()) {
prop.putAll(_jdbcProperties);
}
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection c = DriverManager.getConnection(url, prop);
PreparedStatement pstmt = null;
String sql = null;
sql = myquery;
pstmt = c.prepareStatement(sql);
pstmt.setString(1, "csvźà.py");
pstmt.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
這是檢索代碼。
private void showResults() {
try {
loadJdbcProperties();
String myquery = "select col1 from db.t1";
String url = "jdbc:mysql://localhost:3307/db?useUnicode=true&characterEncoding=Cp1252";
Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "root");
if (_jdbcProperties != null && !_jdbcProperties.isEmpty()) {
prop.putAll(_jdbcProperties);
}
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection c = DriverManager.getConnection(url, prop);
PreparedStatement pstmt = null;
String sql = null;
ResultSet rs = null;
sql = myquery;
pstmt = c.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("col1"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
下面是結果:
csv?à.py
這是因爲根據MySQL文檔,latin1的Java風格字符編碼名稱是Cp1252。 https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-charsets.html – user3566773