Android studio範例程式碼 透過 JTDS 連線 SQL SERVER資料庫
1. 先到http://jtds.sourceforge.net/ 下載JTDS 文件 , 網站上說jtds 1.3.1有些問題,建議抓1.3.1版本以下
2.新增Android studio 專案
3.將下載下來的jtds1.x.x.jar文件放入 Android studio 專案目錄 app\libs 中
4.新增一個java class 如下
package com.kaps.jdbctosqltest;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.*;
public class mssql {
private boolean _isOpened=false;
String ipaddress, db, username, password;
public static Connection connect;
Statement st;
public boolean isOpened()
{
return _isOpened;
}
@SuppressLint("NewApi")
private Connection ConnectionHelper(String user, String password,
String database, String server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + ";"
+ "databaseName=" + database + ";user=" + user
+ ";password=" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return connection;
}
public mssql () {
//設定jdbc連結字串,請依你的SQL Server設定值修改
try {
ipaddress = "203.74.205.57";
db = "test";
username = "sa";
password = "sa";
connect = ConnectionHelper(username, password, db, ipaddress);
if (connect.isClosed()==false)
{
_isOpened=true;
System.out.println("connect ok");
}
else
{
_isOpened=false;
System.out.println("connect fail");
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
5.如此即可在Main class 中透過 mssql.connect 方式呼叫使用 資料庫連線
6.AndroidManifest.xml 需新增授權如下
<uses-permission android:name="android.permission.INTERNET" />
7.重要
關於以上JTDS連線字串 可使用在 ANDROID 4.4版以上 ,但是若是 4.2版以下我測試在連線時會出現ERROR錯誤,訊息為
java.sql.SQLException: Charset 0x0404D00000/MS950 is not supported by the JVM
若要排除以上訊息需在連線字串中加上charset=UTF8,範例如下:
jdbc:jtds:sqlserver://資料庫位置:1433/資料庫名稱;charset=utf8", "帳號", "密碼"
參考網站:
http://blog.csdn.net/yaoneng119/article/details/8859326
https://gotoapp.wordpress.com/2015/01/27/android-android-app-sql-server/