SQLite基本(实例FileOrganizer2013.5.12)
import org.sqlite.JDBC; Connection conn = null; Statement stat; ResultSet rs; // 连接数据库 void connect() { try { // 连接SQLite的JDBC Class.forName("org.sqlite.JDBC"); // 建立一个数据库名zieckey.db的连接,如果不存在就在当前目录下创建之 conn = DriverManager.getConnection("jdbc:sqlite:test.db"); stat = conn.createStatement(); } catch (Exception e) { e.printStackTrace(); } //JOptionPane.showMessageDialog(null,"已连接数据库"); if( null == conn){ JOptionPane.showMessageDialog(null,"连接数据库失败"); System.exit(1); } } // 断开连接 void disconnect() { try { // rs.close(); conn.close();// 结束数据库的连接 } catch (SQLException e) { e.printStackTrace(); } //JOptionPane.showMessageDialog(null, "已断开数据库"); }
读取元数据和数据
private void showMetaData() {//显示数据表头以测试数据库连接 ResultSetMetaData rsmd; //取得元数据 try { rs = stat.executeQuery("Select * From test"); rsmd = rs.getMetaData(); int ColumnCount = rsmd.getColumnCount(); for (int j = 1; j <= ColumnCount; j++) { System.out.println(rsmd.getColumnName(j)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void showDataInTable() {//显示数据 //定义表格的数据模型 DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel(); try { while (rs.next()) { Vector newRow = new Vector(); int c = 1, numberOfColumns; numberOfColumns = rs.getMetaData().getColumnCount(); while (c <= numberOfColumns) { newRow.addElement(rs.getString(c)); c++; } dtm.addRow(newRow); } } catch (Exception e) { e.printStackTrace(); } }
查询指定行
select * from MAIN.[test] where rowid =10;
删除
String updateSql="delete from test where RecID =‘"+(String)jTable1.getValueAt(jTable1.getSelectedRow(),0)+"‘"; try { stat.executeUpdate(updateSql); showDataInTable(); System.out.println("已delete"); } catch (SQLException ex) { ex.printStackTrace(); }
更新
int row = jTable1.getSelectedRow(); String updateSql="update test "// + "set Dept=‘sorry2" + "set Dept=‘"+jTextField2.getText() + "‘, SendID=‘"+jTextField3.getText() + "‘, Title=‘"+jTextField4.getText() + "‘, RecDate=‘"+jTextField5.getText() + "‘, Link=‘"+jTextField6.getText() + "‘ where RecID =‘"+(String)jTable1.getValueAt(row,0)+"‘"; try { stat.executeUpdate(updateSql); showDataInTable(); System.out.println("已save"); } catch (SQLException ex) { ex.printStackTrace(); }
插入
String updateSql="insert into test VALUES(" + "‘"+jTextField1.getText() + "‘,‘"+jTextField2.getText() + "‘,‘"+jTextField3.getText() + "‘,‘"+jTextField4.getText() + "‘,‘"+jTextField5.getText() + "‘,‘"+jTextField6.getText() +"‘)"; try { stat.executeUpdate(updateSql); showDataInTable(); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。