java对sqlite进行插入操作的乱码问题

夜星寒 发布于 2013/06/28 15:35
阅读 2K+
收藏 2

用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;
	}

}

加载中
0
月影又无痕
月影又无痕

 description =newString(source.getBytes(),"utf-8");

注意编码问题

夜星寒
夜星寒
貌似不行啊!依旧乱码........................痛苦呀!!折腾好久了........
0
磨刀砍大帅
插入用gbk  查询用UTF8 可以呢。
返回顶部
顶部