首先下载jtds jar包(http://sourceforge.net/projects/jtds/files/jtds/),我下载的是1.2.7版本的
下载好的jar包放入app/libs 下 然后在app目录下的build.gradle引用jar包
implementation files('libs\\jtds-1.2.7.jar')
关键代码:
private Connection con = null;
private String UserName = "sa";
private String Password = "sa";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectTask = new ConnectTask();
connectTask.execute();
}
class ConnectTask extends AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Object doInBackground(Object[] objects) {
try {
Log.d("======moyujun=====", "connect sql ing...");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.50.115:1433/AndroidSQLTest", UserName, Password);
testQuery(con);
Log.d("======moyujun=====", "success!!!!!!!!!!!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.d("======moyujun=====", "error Class Not Found");
} catch (SQLException throwables) {
throwables.printStackTrace();
System.out.println(throwables.getMessage().toString());
Log.d("======moyujun=====", "error SQLException");
}
return "over";
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
Log.d("onPostExecute", String.valueOf(o));
}
}
public void testQuery(Connection con) throws java.sql.SQLException {
try {
Log.d("======moyujun=====", "connect success");
String sql = "SELECT * FROM test";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Log.d("======moyujun=====", rs.getString("IMEI"));
Log.d("======moyujun=====", rs.getString("SN"));
}
rs.close();
stmt.close();
} catch (SQLException e) {
System.out.println(e.getMessage().toString());
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
}
}
}
}
AndroidManifest.xml里面记得添加权限
<uses-permission android:name="android.permission.INTERNET"/>
|