J2ME 客戶端受限於運算能力,資料庫操作宜放在伺服器端。利用 HttpConnection (GCF 必支援) 呼叫 ASP 頁面,ASP 執行 ADO 操作 Access/SQL Server,回傳結果,實現輕量級行動資料庫應用。
D:\J2ME\J2METEST\IIS\DATABASE\J2MEtest.mdb,資料表 Message:ID(自動編號)、MESSAGE(文字)、IP(文字)、DATE(日期)。ConnectASP.asp 放置於 D:\J2ME\J2METEST\IIS\ASP:<%@ LANGUAGE=VBScript %>
<%
strDBLocation = Server.MapPath("/database/J2METest.mdb")
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strDBLocation
Set cnn = Server.CreateObject("ADODB.Connection")
cnn.Open strConn
Set rs = Server.CreateObject("ADODB.Recordset")
rs.ActiveConnection = cnn
rs.CursorType = 1 : rs.LockType = 2
rs.Source = "Message"
rs.Open
rs.AddNew
rs("Message") = Request.QueryString("message")
rs("IP") = Request.ServerVariables("REMOTE_ADDR")
rs("Date") = Now()
rs.Update
rs.Close : cnn.Close
Response.Write "The message written successfully."
%>
瀏覽器測試:https://localhost/asp/ConnectASP.asp?message=Hello+J2ME 成功寫入資料庫。
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
public class ConnectASP extends MIDlet {
public void startApp() {
try { testASP(); } catch (IOException e) { System.out.println("error"); }
notifyDestroyed();
}
void testASP() throws IOException {
String uri = "https://localhost/ASP/ConnectASP.asp?message=Hello+J2ME!";
HttpConnection conn = null;
InputStream in = null;
try {
conn = (HttpConnection) Connector.open(uri);
in = conn.openInputStream();
int ch;
while ((ch = in.read()) != -1) System.out.print((char) ch);
} catch (Exception e) {
System.out.println("Http could not be opened");
} finally {
try { if (in != null) in.close(); } catch (IOException ignored) {}
try { if (conn != null) conn.close(); } catch (IOException ignored) {}
}
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
}
主控台輸出 The message written successfully.,資料庫新增一筆記錄(ID=1, Message=Hello J2ME, IP=127.0.0.1, Date=當前日期)。
localhost。