本文將介紹開發Android程序,連接SQL Server,通過第三方包jtds的方式。
如果你有同樣的需求,請跟着做一遍,博主將以最詳細的方式,進行介紹。
首先說明,Java、Android連接SQL Server並不是常見的方式,原因是SQL Server的微軟的產品,沒有打算讓Java、Android直接連接,所以能連上的,都是在Java、Android使用第三方的包,
目前總共有2個方法能連,(1)本文將介紹jtds,這是名副其實的直連,Android必須使用1.2.7版本,高版本連不了,Java則可以使用1.3.1
(2)通過ASP.NET的web service連接,這個並非直連,只是通過網頁讀取,Java使用第三方包axis,Android使用KSOAP。(以后的文章會介紹)
博主由於工作的原因,兩種方法都試過了,因此分享到這里。
下面正式開始說明:
首先,先說明一下普通的操作步驟:
一、打開AndroidManifest.xml的網絡操作權限
這是博主在之前的文章強調過的,這個必須先打開,以免以后遺忘。

1 <?xml version="1.0" encoding="utf-8"?>
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3 package="com.test.androidsqltest"
4 android:versionCode="1"
5 android:versionName="1.0" >
6
7 <uses-permission android:name="android.permission.INTERNET" />
8
9 <uses-sdk 10 android:minSdkVersion="14"
11 android:targetSdkVersion="21" />
12
13 <application 14 android:allowBackup="true"
15 android:icon="@drawable/ic_launcher"
16 android:label="@string/app_name"
17 android:theme="@style/AppTheme" >
18 <activity 19 android:name=".MainActivity"
20 android:label="@string/app_name" >
21 <intent-filter>
22 <action android:name="android.intent.action.MAIN" />
23
24 <category android:name="android.intent.category.LAUNCHER" />
25 </intent-filter>
26 </activity>
27 </application>
28
29 </manifest>
二、導入jtds包
1、在項目路徑下建立libs文件夾,把jtds-1.2.7.jar放到libs目錄中
2、右鍵點擊項目名=>Build Path=>Configure Build Path=>上面打開Libraries=>Add External JARs
=>選中jtds-1.2.7.jar=>上面打開Order and Export=>勾選jtds-1.2.7.jar=>apply
完成
三、簡單界面布局
1、res=>values=>strings.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <resources>
3
4 <string name="app_name">JtdsTest</string>
5 <string name="hello_world">Hello world!</string>
6 <string name="action_settings">Settings</string>
7 <string name="btnInsert">Insert</string>
8
9 </resources>
界面中的Button,顯示文本為Insert
2、res=>layout=>activity_main.xml
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:paddingBottom="@dimen/activity_vertical_margin"
6 android:paddingLeft="@dimen/activity_horizontal_margin"
7 android:paddingRight="@dimen/activity_horizontal_margin"
8 android:paddingTop="@dimen/activity_vertical_margin"
9 tools:context="com.test.jtdstest.MainActivity" >
10
11 <TextView 12 android:id="@+id/textView1"
13 android:layout_width="wrap_content"
14 android:layout_height="wrap_content"
15 android:text="@string/hello_world" />
16
17 <Button 18 android:id="@+id/btnInsert"
19 android:layout_width="wrap_content"
20 android:layout_height="wrap_content"
21 android:layout_marginStart="50dp"
22 android:layout_marginLeft="50dp"
23 android:layout_marginTop="40dp"
24 android:text="@string/btnInsert" />
25
26 </RelativeLayout>
加入Button控件
3、主程序代碼(增Insert、刪Delete、改Update)
1 package com.test.jtdstest; 2
3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.SQLException; 7
8 import android.app.Activity; 9 import android.os.Bundle; 10 import android.os.Handler; 11 import android.view.Menu; 12 import android.view.MenuItem; 13 import android.view.View; 14 import android.view.View.OnClickListener; 15 import android.widget.Button; 16 import android.widget.Toast; 17
18 public class MainActivity extends Activity { 19
20 // 按鈕控件
21 private Button btnInsert; 22 // jtds驅動路徑
23 private String drive = "net.sourceforge.jtds.jdbc.Driver"; 24 // SQL連接字符串,格式是 jdbc:jtds:sqlserver://服務器IP:端口號/數據庫名稱 25 // 端口號默認為1433,如果不是,可以打開SQL Server配置管理器設定, 26 // 如果你的SQL Server不是默認實例,需添加連接字符串為 27 // jdbc:jtds:sqlserver://服務器IP:端口號/數據庫名稱;instance=實例名,不過博主沒有試驗過,你可以百度一下。
28 private String connStr = "jdbc:jtds:sqlserver://10.76.25.1:1433/CommonDB"; 29 // 用戶名和密碼,則是對應的數據庫的帳號,博主使用sa進行說明,如果你用的不是sa,記得在數據庫表中打開你的帳號的權限。
30 private String uid = "sa"; 31 private String pwd = "123"; 32 // 連接對象,相當於C#中的SqlConnection
33 private Connection con = null; 34 // 執行對象,相當於C#中的SqlCommand
35 private PreparedStatement pstm = null; 36 // handler處理對象,用於在跨線程時,在線程間的響應,用於控制主線程的控件(不能跨線程控制控件)
37 private Handler handler = new Handler(); 38
39 // 執行語句
40 private String sql = "insert into [table1]([id],[name]) values ('01','aaa')"; 41 // 執行結果,受影響行數
42 private int resultCount; 43
44 @Override 45 protected void onCreate(Bundle savedInstanceState) { 46 super.onCreate(savedInstanceState); 47 setContentView(R.layout.activity_main); 48
49 // 找到btnInsert按鈕
50 btnInsert = (Button) findViewById(R.id.btnInsert); 51 // 設定btnInsert的click操作的監聽事件,btnInsert被點擊時,觸發clickEvent()方法
52 btnInsert.setOnClickListener(clickEvent()); 53 } 54
55 // clickEvent()方法
56 public OnClickListener clickEvent() { 57 return new OnClickListener() { 58
59 // 方法體
60 @Override 61 public void onClick(View view) { 62 // TODO Auto-generated method stub
63 if (view == btnInsert) { 64 // 必須開啟新的線程執行
65 Thread thread = new Thread(new Runnable() { 66
67 @Override 68 public void run() { 69 // TODO Auto-generated method stub 70 // 線程在運行后,執行Insert()方法,返回受影響行數,賦值給resultCount
71 resultCount = Insert(); 72 // 使用handler,使主線程響應並執行runShowResult方法
73 handler.post(runShowResult); 74 } 75 }); 76 // 線程運行
77 thread.start(); 78 } 79 } 80 }; 81 } 82
83 // 操作數據庫的方法
84 public int Insert() { 85 int count = 0; 86 try { 87 // 加載驅動
88 Class.forName(drive); 89 } catch (ClassNotFoundException e) { 90 // TODO Auto-generated catch block
91 e.printStackTrace(); 92 } 93
94 try { 95 // 創建連接對象,加入連接字符串、用戶名、密碼
96 con = DriverManager.getConnection(connStr, uid, pwd); 97 // 創建執行對象,並加入執行語句
98 pstm = con.prepareStatement(sql); 99 // 執行SQL語句,並返回受影響行數
100 count = pstm.executeUpdate(); 101 } catch (SQLException e) { 102 // TODO Auto-generated catch block
103 e.printStackTrace(); 104 count = -1; 105 } finally { 106 try { 107 // 關閉連接
108 pstm.close(); 109 con.close(); 110 } catch (Exception e2) { 111 // TODO: handle exception
112 e2.printStackTrace(); 113 } 114 } 115 return count; 116 } 117
118 // 主線程響應方法,用於顯示提示氣泡
119 public Runnable runShowResult = new Runnable() { 120
121 @Override 122 public void run() { 123 // TODO Auto-generated method stub
124 String tips = "受影響行數為:" + resultCount; 125 // 彈出氣泡
126 Toast.makeText(getApplicationContext(), tips, Toast.LENGTH_SHORT).show(); 127 } 128 }; 129
130 // 暫不需要理會
131 @Override 132 public boolean onCreateOptionsMenu(Menu menu) { 133 // Inflate the menu; this adds items to the action bar if it is present.
134 getMenuInflater().inflate(R.menu.main, menu); 135 return true; 136 } 137
138 // 暫不需要理會
139 @Override 140 public boolean onOptionsItemSelected(MenuItem item) { 141 // Handle action bar item clicks here. The action bar will 142 // automatically handle clicks on the Home/Up button, so long 143 // as you specify a parent activity in AndroidManifest.xml.
144 int id = item.getItemId(); 145 if (id == R.id.action_settings) { 146 return true; 147 } 148 return super.onOptionsItemSelected(item); 149 } 150 }
說明:
1、加載驅動時,如果報錯,則說明jtds包導入失敗,字符串沒有錯誤的情況下,一定能加載成功;
2、如果使用的數據庫實例,並不是默認實例,需在連接字符串加入;instance=實例名
3、必須使用跨線程進行網絡操作,因為Android4.0后,就禁止在主線程進行網絡操作,因為如果操作失敗,將導致整個程序崩潰。
4、得到的執行結果,可用公共變量接收,如上面代碼的resultCount,在副線程賦值給resultCount后,可直接通過Handler對象,調用Runnable方法,操作主線程的控件,上面代碼把結果顯示在Toast中。
常見的運行失敗現象:
1、Thread跳出,程序中止,說明在處理控件與線程時出現異常
2、EACCES permission,就是AndroidManifest.xml沒有插入打開網絡權限的語句
如果運行錯誤,而找不到錯誤發生在哪里,可以在代碼中各步加入System.out.println("標記信息或Exception信息"),在eclipse中打開LogCat監視窗體,觀察運行的情況。
完成,執行看看吧。
以上就是jtds增刪改的代碼說明,還有查詢的方法,由於代碼量不少,所以會在之后的(Android 連接 SQL Server (jtds方式)——下)進行說明。