Thursday, September 10, 2015

Direct access to SQL Server From Android

Sử dụng thư viện JTDS --> http://sourceforge.net/projects/jtds/  để truy cập SQL Server từ Android

[embed]https://youtu.be/8cp8ykUNmL4[/embed]

Download thư viện từ đây

Kết nối với SQL Server như sau:
[sourcecode language="java"]
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
conn = DriverManager
.getConnection(""
+ "jdbc:jtds:sqlserver://172.16.160.81/northwind;instance=SQL2008;"
+ "user=sa;password=sa;");
[/sourcecode]

net.sourceforge.jtds.jdbc.Driver là dạng Drive truy cập SQL Server.

Thêm dữ liệu

[sourcecode language="java"]
comm = conn.prepareStatement("insert into Employees("
+ "firstname, lastname) values(?,?)");
comm.setString(1, etFirst.getText().toString());
comm.setString(2, etLast.getText().toString());
comm.executeUpdate();
[/sourcecode]

Đọc dữ liệu

[sourcecode language="java"]
comm = conn.createStatement();
ResultSet rs = comm.executeQuery("Select EmployeeID, Firstname From Employees");
String msg = "";
while (rs.next()) {
msg += "\nID: " + rs.getInt("EmployeeID") + " Name: "
+ rs.getString("Firstname");
[/sourcecode]

Giao diện

[sourcecode language="html"]
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >

<EditText
android:id="@+id/etFirstName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:background="#eeeeee"
android:hint="Firstname"
android:textColor="#000000"
android:textSize="24dp" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/etLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeeeee"
android:hint="Lastname"
android:padding="4dp"
android:textColor="#000000"
android:textSize="24dp" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp" >

<Button
android:id="@+id/btnConnect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Connect" />

<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Add new" />
</LinearLayout>

<TextView
android:id="@+id/tvDs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:padding="8dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
[/sourcecode]

Mã nguồn tham khảo https://drive.google.com/file/d/0B2F9IAasWwaNYVZSc2tiZDNlNTA/view?usp=sharing

No comments:

Post a Comment

Translate