ServiceDBHelper
此類別為自訂類別, 請由專案新增class, 並將如下代碼鍵入.
此類別用來跟資料庫伺服器進行連線, 在Class中, Class.forName(“net.sourceforge.jtds.jdbc.Driver”); 此行就是載入驅動程式的意思
jtds適用於Android 4.4以上(含), 若低於此版本, 在連線時會出現錯誤, 所以需在連線字串加上 charset=utf8;
public class ServerDBHelper {
private Connection connection;
private String server;
private String database;
private String userAccount;
private String userPassword;
Handler handler;
public ServerDBHelper(Handler handler, String server, String database, String userAccount, String userPassword){
this.handler=handler;
this.server=server;
this.database=database;
this.userAccount=userAccount;
this.userPassword=userPassword;
}
private Connection connectionHelper() throws SQLException, ClassNotFoundException{
StrictMode.ThreadPolicy policy = (new StrictMode.ThreadPolicy.Builder()).permitAll().build();
StrictMode.setThreadPolicy(policy);
String connectionURL = null;
Class.forName("net.sourceforge.jtds.jdbc.Driver");
if (Build.VERSION.SDK_INT >= 19) {
connectionURL = String.format("jdbc:jtds:sqlserver://%s;databaseName=%s;user=%s;password=%s;", this.server, this.database, this.userAccount, this.userPassword);
} else {
connectionURL = String.format("jdbc:jtds:sqlserver://%s;databaseName=%s;charset=utf8;user=%s;password=%s;", this.server, this.database, this.userAccount, this.userPassword);
}
return DriverManager.getConnection(connectionURL);
}
public Connection makeConnection(){
try{
if(connection!=null && !connection.isClosed()){
connection.close();
}
connection=this.connectionHelper();
return connection;
}
catch(SQLException e){
Log.d("Thomas", e.getMessage());
}
catch(ClassNotFoundException e){
Log.d("Thomas", e.getMessage());
}
return null;
}
}
網路權限
因為連線到遠端資料庫伺服器, 需使用到網路, 所以記得在AndroidManifest.xml加上權限
<uses-permission android:name=“android.permission.INTERNET” />
用法
ServiceDBHelper為常用的類別, 所以上面的設計, 只需傳入handler, ip, 資料庫, 帳號, 密碼, 就可取得連線物件 .
因此會建議大家把此類別放入您自已的SDK內, 日後只要import即可使用. 像本人也好久沒在摸個類別了, 都快忘了當初怎麼寫出來的.
在主程式中, 只要產生ServiceDBHelper, 再調用makeConnection即可, 如下
serverDBHelper=new ServerDBHelper(handler, "ip", "資料庫", "帳號", "密碼"); Connection conn=serverDBHelper.makeConnection();