雖然Android採用標準SQLite資料庫儲存資料,並藉由資料庫存取local端應用程式資料內容,以減少使用open/write file等方式去讀取資料,所以它是屬於較輕量級的資料庫,且應用面也與重量級的MySQL/PostgreSQL/MS-SQL有所差異,由官方說法中也可以了解SQLite並不是為了取代上述這些資料庫而開發。
原使用者資料建立在Local端的SQLite中,但由於資料不易管理,且後續以它當作大型資料庫控管應該是比較奇怪的作法,更何況nand flash存取的限定,不得不使用PostgreSQL或MySQL控管資料。
實作方法可參照 http://caterpillar.onlyfun.net/Gossip/JavaGossip-V2/ConnectDB.htm,以下是程式實例:
public CharSequence[] QueryTotalUser(){
CharSequence[] list = null;
Connection conn = CreateSQLConn();
if(conn != null)
System.out.println("Successfully connected to Postgres Database");
else
System.out.println("We should never get here.");
try
{
int index = 0;
String query = "SELECT * FROM apas";
Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery(query);
rs.last();
list = new CharSequence[rs.getRow()];
rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
while(rs.next())
{
list[index] = rs.getString("cardid");
Log.i("Postgres", "Query=>" + list[index]);
System.out.println("Here's the result of row " + index++ + ":");
}
rs.close();
conn.close();
st.close();
}catch (SQLException ex)
{
System.err.println(ex.getMessage());
}
return list;
}
public Connection CreateSQLConn(){
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");// Dynamic load JDBC driver
}catch (ClassNotFoundException cnfe) {
System.err.println("Couldn't find driver class.");
cnfe.printStackTrace();
}
try{
conn = DriverManager.getConnection("jdbc:postgresql://192.168.1.100:5432/users",
"postgres", "tmdwbd");// With JDBC, a database is represented by a URL
}catch (SQLException se) {
System.out.println("Couldn't connect: print out a stack trace and exit.");
se.printStackTrace();
}
return conn;
}
