說明:

本文改上一篇:SQLite SELECT TABLE Using Java

,改為使用PreparedStatement。





一、建立 SELECT  TABLE SQL



public static String getSelectSql() {
return "SELECT * FROM CUSTOMER WHERE CUS_ID = ?;";
}




二、程式



package com.sqlite.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SelectTableSQLiteJDBC2 {

public static String getSelectSql() {
return "SELECT * FROM CUSTOMER WHERE CUS_ID = ?;";
}

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(getSelectSql());
ps.setString(1, "1");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int cusId = rs.getInt("CUS_ID");
String cusName = rs.getString("CUS_NAME");
int cusAge = rs.getInt("CUS_AGE");
String cusAddress = rs.getString("CUS_ADDRESS");
float salary = rs.getFloat("salary");
System.out.println("CUS_ID = " + cusId);
System.out.println("CUS_NAME = " + cusName);
System.out.println("CUS_AGE = " + cusAge);
System.out.println("CUS_ADDRESS = " + cusAddress);
System.out.println("SALARY = " + salary);
System.out.println();
}
c.commit();
System.out.println("SELECT 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





五、相關文章

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















































其它文章





arrow
arrow
    創作者介紹
    創作者 PG Levin Li 的頭像
    PG Levin Li

    程式開發學習之路

    PG Levin Li 發表在 痞客邦 留言(0) 人氣()