Eclispse + SqlServer2008R2java
只能下載1.2.7版本的,將 jtds-1.2.7.jar 包放在android項目 libs 目錄下。 下載地址:http://sourceforge.net/projects/jtds/files/android
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBUtil { private static String IP = "192.168.1.1"; private static String DBName = "Test"; private static String USER = "sa"; private static String PWD = "123"; /** 建立數據庫對象 */ private static Connection getSQLConnection() { Connection con = null; try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); //加上 useunicode=true;characterEncoding=UTF-8 防止中文亂碼 con = DriverManager.getConnection("jdbc:jtds:sqlserver://" + IP + ":1433/" + DBName + ";useunicode=true;characterEncoding=UTF-8", USER, PWD); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return con; } /** 查詢數據庫 */ public static String Query() { String result = ""; try { Connection conn = getSQLConnection(); String sql = "select * from SysUser"; Statement stmt = conn.createStatement();// ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String s1 = rs.getString("UserCode"); String s2 = rs.getString("RealName"); result += s1 + " - " + s2 + "\n"; } rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); result += "查詢數據異常!" + e.getMessage(); } return result; } }
一個Buttton控件,用來點擊查詢。
一個TextView控件,用來顯示查詢到的信息。
代碼省略。。。sql
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { Button button; TextView textview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); textview = (TextView) findViewById(R.id.textview); // 按鈕點擊事件 button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { textview.setText(""); test(); } }); } // 查詢 private void test() { Runnable run = new Runnable() { @Override public void run() { String ret = DBUtil.Query(); Message msg = new Message(); msg.what = 1001; Bundle data = new Bundle(); data.putString("result", ret); msg.setData(data); mHandler.sendMessage(msg); } }; new Thread(run).start(); } // 消息顯示到控件 Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 1001: String str = msg.getData().getString("result"); textview.setText(str); break; default: break; } }; }; }
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />