//先下載JTDS JDBC DRIVER 放到PROJECT 的LIBRARY中
package com.example.sqlconntest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//import com.example.sqlconntest.R;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity
{
private String UserName = "sa";
private String Password = "111";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectTask dt = new ConnectTask();
dt.execute();
}
class ConnectTask extends AsyncTask<Integer, Integer, String>
{
Connection con = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Integer... params) {
TextView tv;
tv=(TextView)findViewById(R.id.textView1);
//建立資料庫連接
try {
Class.forName( "net.sourceforge.jtds.jdbc.Driver");
con = DriverManager.getConnection( "jdbc:jtds:sqlserver://10.0.2.2:1433/travel", UserName, Password);
//10.0.2.2是使用模擬器的PC本機IP,TRAVEL 是我的DB NAME
testConnection(con);
tv.setText("連結資料庫成功!");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
tv.setText("Driver error");
Log.e("Class.forName::ClassNotFoundException", e1.getMessage());
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tv.setText("Connection Error");
}
return "OK";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
public void testConnection(Connection con) throws java.sql.SQLException {
try {
String sql = "SELECT * FROM 景點資料 Where Region='台北市'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Log.e("&&&&&", rs.getString("NameChs"));
Log.e("&&&&&", rs.getString("OperateUserName"));
}
rs.close();
stmt.close();
} catch (SQLException e) {
System.out.println(e.getMessage().toString());
} finally {
if (con != null)
try {
con.close();
} catch (SQLException e) {
}
}
}
}
}
沒有留言:
張貼留言