網上很多人都說這種做法是不合理的,其實我也是這麼覺得的,因爲安全得不到保障,而且對數據庫操作的業務邏輯不可能都放在Android斷,這樣會對APP造成很大壓力。但是我們項目精靈非要做,於是我們就硬着頭皮做了,也測試通了,我這裏提供兩個版本的DEMO,一個是連接內網,一個是連接外網,目前只在模擬器上測試過,真機不敢保證
附註:我的代碼是參照別人的,本來想列舉鏈接的,但是找不到了,如果以後找到原文鏈接,我一定補上。
首先是內網版(Eclipse):
package com.example.jdbctest;
import java.sql.Connection;
import java.sql.SQLException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class TestActivity extends Activity {
private static final String REMOTE_IP = "192.168.1.7";//服務器地址
private static final String URL = "jdbc:mysql://" + REMOTE_IP + "/zw";
private static final String USER = "root";//數據庫賬戶
private static final String PASSWORD = "root";//數據庫密碼
private Connection conn;
public void onConn(View view) {
new Thread() {
public void run() {
Log.e("============", "你麻痹");
conn = Util.openConnection(URL, USER, PASSWORD);
}
}.start();
}
public void onInsert(View view) {
new Thread() {
public void run() {
Log.e("============", "你麻痹的插入");
String sql = "insert into users values(3, 'yinhongbo', 'yinhongbo')";
Util.execSQL(conn, sql);
}
}.start();
}
public void onDelete(View view) {
String sql = "delete from mytable where name='mark'";
Util.execSQL(conn, sql);
}
public void onUpdate(View view) {
String sql = "update mytable set name='lilei' where name='hanmeimei'";
Util.execSQL(conn, sql);
}
public void onQuery(View view) {
new Thread() {
public void run() {
Log.e("============", "你麻痹的查詢");
Util.query(conn, "select * from users");
}
}.start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
conn = null;
} finally {
conn = null;
}
}
}
}
Util類:
package com.example.jdbctest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.util.Log;
public class Util {
public static Connection openConnection(String url, String user,
String password) {
Connection conn = null;
try {
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
Class.forName(DRIVER_NAME);
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
conn = null;
} catch (SQLException e) {
conn = null;
}
return conn;
}
public static void query(Connection conn, String sql) {
if (conn == null) {
Log.e("======conn結果======", "conn = null");
return;
}
Statement statement = null;
ResultSet result = null;
try {
statement = conn.createStatement();
result = statement.executeQuery(sql);
if (result != null && result.first()) {
int idColumnIndex = result.findColumn("id");
int nameColumnIndex = result.findColumn("user_name");
Log.e("======結果======", "結果");
while (!result.isAfterLast()) {
Log.e("======id======", result.getString(idColumnIndex) + "\t\t");
Log.e("======name======", result.getString(nameColumnIndex));
// System.out.print(result.getString(idColumnIndex) + "\t\t");
// System.out.println(result.getString(nameColumnIndex));
result.next();
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (result != null) {
result.close();
result = null;
}
if (statement != null) {
statement.close();
statement = null;
}
} catch (SQLException sqle) {
}
}
}
public static boolean execSQL(Connection conn, String sql) {
boolean execResult = false;
if (conn == null) {
return execResult;
}
Statement statement = null;
try {
statement = conn.createStatement();
if (statement != null) {
execResult = statement.execute(sql);
}
} catch (SQLException e) {
execResult = false;
}
return execResult;
}
}
外網版(Android Studio):
package com.jingchujie.jdbctestinas;
import java.sql.Connection;
import java.sql.SQLException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
// private static final String REMOTE_IP = "192.168.1.7";
// private static final String URL = "jdbc:mysql://" + REMOTE_IP + "/zw";
// private static final String USER = "root";
// private static final String PASSWORD = "root";
private static final String REMOTE_IP = "localhost:33104";//這裏是映射地址,可以隨意寫,不是服務器地址
private static final String URL = "jdbc:mysql://" + REMOTE_IP + "/mobile";
private static final String USER = "root";
private static final String PASSWORD = "";
private Connection conn;
public void onConnSsh(View view) {
new Thread() {
public void run() {
Log.e("============", "預備連接服務器");
Util.go();
}
}.start();
}
public void onConn(View view) {
new Thread() {
public void run() {
Log.e("============", "預備連接數據庫");
conn = Util.openConnection(URL, USER, PASSWORD);
}
}.start();
}
public void onInsert(View view) {
new Thread() {
public void run() {
Log.e("============", "預備插入");
String sql = "insert into users values(3, 'yinhongbo', 'yinhongbo')";
Util.execSQL(conn, sql);
}
}.start();
}
public void onDelete(View view) {
String sql = "delete from mytable where name='mark'";
Util.execSQL(conn, sql);
}
public void onUpdate(View view) {
String sql = "update mytable set name='lilei' where name='hanmeimei'";
Util.execSQL(conn, sql);
}
public void onQuery(View view) {
new Thread() {
public void run() {
Log.e("============", "預備查詢");
Util.query(conn, "select * from users");
}
}.start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
conn = null;
} finally {
conn = null;
}
}
}
}
Util類
package com.jingchujie.jdbctestinas;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.util.Log;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class Util {
public static void go() {
String user = "root";//SSH連接用戶名
String password = "1q2w3e";//SSH連接密碼
String host = "192.168.1.4";//SSH服務器
int lport = 33104;//本地端口(隨便取)
String rhost = "localhost";//遠程MySQL服務器
int rport = 3306;//遠程MySQL服務端口
int port = 22;//SSH訪問端口
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Log.e("=======>", "服務器連接成功");
System.out.println(session.getServerVersion());//這裏打印SSH服務器版本信息
int assinged_port = session.setPortForwardingL(lport, rhost, rport);//將服務器端口和本地端口綁定,這樣就能通過訪問本地端口來訪問服務器
System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection openConnection(String url, String user,
String password) {
Connection conn = null;
try {
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
Class.forName(DRIVER_NAME);
conn = DriverManager.getConnection(url, user, password);
Log.e("=====連接結果=======", "數據庫連接成功");
} catch (ClassNotFoundException e) {
Log.e("=====連接結果=======", "報ClassNotFoundException異常");
conn = null;
} catch (SQLException e) {
Log.e("=====連接結果=======", "報SQLException異常");
conn = null;
}
return conn;
}
public static void query(Connection conn, String sql) {
if (conn == null) {
Log.e("=====連接前判斷=======", "conn == null");
return;
}
Statement statement = null;
ResultSet result = null;
try {
statement = conn.createStatement();
result = statement.executeQuery(sql);
if (result != null && result.first()) {
int idColumnIndex = result.findColumn("id");
int nameColumnIndex = result.findColumn("user_name");
Log.e("======結果======", "結果");
while (!result.isAfterLast()) {
Log.e("======id======", result.getString(idColumnIndex) + "\t\t");
Log.e("======name======", result.getString(nameColumnIndex));
// System.out.print(result.getString(idColumnIndex) + "\t\t");
// System.out.println(result.getString(nameColumnIndex));
result.next();
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (result != null) {
result.close();
result = null;
}
if (statement != null) {
statement.close();
statement = null;
}
} catch (SQLException sqle) {
}
}
}
public static boolean execSQL(Connection conn, String sql) {
boolean execResult = false;
if (conn == null) {
return execResult;
}
Statement statement = null;
try {
statement = conn.createStatement();
if (statement != null) {
execResult = statement.execute(sql);
}
} catch (SQLException e) {
execResult = false;
}
return execResult;
}
}
源碼地址:
內網版(Eclipse):http://download.csdn.net/detail/y280903468/9535368
外網版(Android studio):http://download.csdn.net/detail/y280903468/9535374