最近开发 无线POS机 的数据管理系统,因POS里使用sqlite数据库,且中文显示乱码,故用java写了sqlite的数据库读入JTable中,将中文乱码正确读出,技术拙劣,望君勿笑!
下面是关键代码:
(连sqlite数据库需第三方包:sqlitejdbc-v056.jar)
1 try {
2 Class.forName("org.sqlite.JDBC");
3 Connection con=DriverManager.getConnection("jdbc:sqlite:/"+filePath); //filePath---sqlite数据库的路径,网络路径或者本地路径都可
4 stmtpos = con.createStatement();
5 rspos1=stmtpos.executeQuery("sql...........");
6 Vector datea=new Vector(rspos1.getMetaData().getColumnCount());
7 columnHeaders=new Vector(rspos1.getMetaData().getColumnCount());
8 for(i=1;i<=rspos1.getMetaData().getColumnCount();i++)
9 { columnHeaders.addElement(rspos1.getMetaData().getColumnName(i));
10 System.out.println(rspos1.getMetaData().getColumnName(i));}
11
12 while(rspos1.next())
13 {
14
15 Vector rowData = new Vector(rspos1.getMetaData().getColumnCount());
16 for(i=1;i<=rspos1.getMetaData().getColumnCount();i++)
17 {
18 try {
19 if(rspos1.getBytes(i)==null) //判断当前是否有内容
20 str="";
21 else
22 str=new String(rspos1.getBytes(i),"GBK"); //关键,sqlite里的乱码转换就靠他,一定要用GBK编码转换
23
24 } catch (UnsupportedEncodingException e) {
25 // TODO Auto-generated catch block
26 e.printStackTrace();
27 }
28 rowData.addElement(str);
29
30 }
31 tableData.addElement(rowData);}
32 JTable1.setModel(new DefaultTableModel(tableData,columnHeaders));
33 } catch (ClassNotFoundException e) {
34 // TODO Auto-generated catch block
35 e.printStackTrace();
36 } catch (SQLException e) {
37 // TODO Auto-generated catch block
38 e.printStackTrace();
39 }