用java连接sqlite数据库之后,将sql语句转码utf-8之后使用statement.executeUpdate()插入中文是乱码,转码后读取出来也是乱码。但是如果从命令行插入中文条目,在程序中进行转码后可正常显示中文。求教怎么才能在java程序中正常地插入中文到sqlite中.......
代码如下:
package manager; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SqliteManager { /** * @param args */ public static void main(String[] args) { String sql = "pragma foreign_keys=on"; String description = null; String source = "insert into sct values(100212,1001,8,'一般')"; try { description = new String(source.getBytes(), "utf8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } SqliteManager manager = new SqliteManager(); manager.init(); Connection con = manager.getConnection(); manager.update(sql, con); manager.update("delete from sct where sid=100212 and cid=1001", con);// 删除记录 manager.update(description, con);// 添加记录 ResultSet set = manager.query("select * from sct", con);// 查询记录 try { while (set.next()) { String sid = new String(set.getBytes("sid"), "GBK"); String cid = new String(set.getBytes("cid"), "GBK"); String assess = new String(set.getBytes("assess"), "GBK"); String desp = new String(set.getBytes("description"), "GBK"); System.out.println("sid: " + sid + "\tcid: " + cid + "\tassess: " + assess + "\tdesp: " + desp); } } catch (Exception e) { e.printStackTrace(); } } public void init() { try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public Connection getConnection() { Connection con = null; try { con = DriverManager.getConnection("jdbc:sqlite:" + "/e:/sqlite3/assesssp1.db"); } catch (SQLException e) { e.printStackTrace(); } return con; } public void close(Connection con) { try { if (con != null && !con.isClosed()) { con.close(); } } catch (SQLException e) { e.printStackTrace(); } } public ResultSet query(String sql, Connection connection) { Statement statement; ResultSet result = null; try { statement = connection.createStatement(); statement.setQueryTimeout(100); result = statement.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } return result; } public int update(String sql, Connection connection) { Statement statement; int result = 0; try { statement = connection.createStatement(); statement.setQueryTimeout(100); result = statement.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } return result; } }
description =newString(source.getBytes(),"utf-8");
注意编码问题 ######貌似不行啊!依旧乱码........................痛苦呀!!折腾好久了........######插入用gbk 查询用UTF8 可以呢。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。