說明:
本文改上一篇:SQLite INSERT TABLE Using Java
,改為使用PreparedStatement。
一、建立 INSERT TABLE SQL
public static String getInsertSql() { return "INSERT INTO CUSTOMER (CUS_ID,CUS_NAME,CUS_AGE,CUS_ADDRESS,SALARY) " + "VALUES (?,?,?,?,?);"; }
二、程式
package com.sqlite.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class InsertTableSQLiteJDBC2 { public static String getInsertSql() { return "INSERT INTO CUSTOMER (CUS_ID,CUS_NAME,CUS_AGE,CUS_ADDRESS,SALARY) " + "VALUES (?,?,?,?,?);"; } public static void main(String args[]) { Connection c = null; PreparedStatement ps = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:data/test.db"); c.setAutoCommit(false); ps = c.prepareStatement(getInsertSql()); String cusId = "2"; String cusName = "levin2"; String cusAge = "23"; String cusAddress = "新北市"; String salary = "2000.15"; ps.setString(1, cusId); ps.setString(2, cusName); ps.setString(3, cusAge); ps.setString(4, cusAddress); ps.setString(5, salary); ps.executeUpdate(); c.commit(); System.out.println("INSERT Table successfully."); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } finally { try { if (null != ps) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (null != c) { c.close(); } } catch (SQLException e) { e.printStackTrace(); } } System.exit(0); } }
三、建立測試專案
參考:Java Using SQLite
四、執行程式
圖1
五、查看資料
參考:SQLite Manager For Firefox
圖2
五、相關文章
Java Using SQLite
SQLite CREATE TABLE Using Java
SQLite INSERT TABLE Using Java
SQLite SELECT TABLE Using Java
SQLite UPDATE TABLE Using Java
SQLite DELETE TABLE Using Java
其它文章
沒有留言:
張貼留言