如何通过Android应用程序中的JDBC连接到远程MySQL服务器

时间:2013-03-20 18:06:41

标签: java android mysql jdbc

我想出了如何在Java应用程序中连接到我的远程MySQL服务器。我非常了解这一点。我提供了我的代码和我采取的相同步骤,但是来自Android应用程序。

问题我的代码没有连接有什么问题?我在Java中使用了类似的过程,它的工作非常精彩。

1)我在项目属性中添加了mysql-connector.jar的外部JAR文件(我使用5.1我相信)。这很好,因为我在我的Java应用程序中使用它并且它与它连接。

2)下面是连接和查询数据库的代码。我遗漏了查询信息和服务器信息,替换为<取代。显然:P

3)当我在手机上运行应用程序时,我收到此消息:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通讯链接失败。

4)我在Ubuntu服务器上运行wireshark,只是在侦听mysql端口时看到SSTP条目。

package com.example.test_android;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    private static final String url = "jdbc:mysql://<server ip>:<sql port#>/<database name>";
    private static final String user = "<username>";
    private static final String pass = "<password>";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         testDB();


    }//end oncreate method


    public void testDB() {
        TextView tv = (TextView)this.findViewById(R.id.text_view);
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, pass);
            /* System.out.println("Database connection success"); */

            String result = "Database connection success\n";
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM <table in database>");
            ResultSetMetaData rsmd = rs.getMetaData();

            while(rs.next()) {
                result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
                result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
                result += rsmd.getColumnName(3) + ": " + rs.getString(3) + "\n";
            }
            tv.setText(result);
        }
        catch(Exception e) {
            e.printStackTrace();
            tv.setText(e.toString());
        }   

    }

}//end class

5)堆栈跟踪:

03-20 11:50:46.381: W/SurfaceFlinger(334): id=54501 Removed idx=5 Map Size=4
03-20 11:50:46.381: D/memalloc(334): ion: Freeing buffer base:0x42fb0000 size:1228800 fd:50
03-20 11:50:46.381: D/memalloc(334): ion: Freeing buffer base:0x43107000 size:1228800 fd:11
03-20 11:50:46.381: W/SurfaceFlinger(334): id=54501 Removed idx=-2 Map Size=4
03-20 11:50:46.381: D/memalloc(334): ion: Freeing buffer base:0x43c2d000 size:1228800 fd:53
03-20 11:50:46.381: D/KeyguardViewMediator(648): setHidden false
03-20 11:50:47.302: E/MP-Decision(1366): DOWN Ld:51 Ns:1.100000 Ts:190 rq:1.000000 seq:196.000000
03-20 11:50:47.492: D/STATUSBAR-NetworkController(805): onReceive() - RSSI_CHANGED_ACTION, WIFI_STATE, NETWORK_STATE
03-20 11:50:48.143: E/SMD(330): DCD ON
03-20 11:50:48.603: V/WindowOrientationListener(648): nearestRotation : 0   Angle: 348   tilt: 45
03-20 11:50:50.535: D/STATUSBAR-NetworkController(805): onReceive() - RSSI_CHANGED_ACTION, WIFI_STATE, NETWORK_STATE
03-20 11:50:50.555: E/MP-Decision(1366): UP Ld:50 Nw:1.990000 Tw:140 rq:2.700000 seq:147.000000
03-20 11:50:50.946: W/dalvikvm(23747): VFY: unable to find class referenced in signature (Ljavax/naming/Reference;)
03-20 11:50:50.946: I/dalvikvm(23747): Could not find method javax.naming.Reference.get, referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.initializeFrom
03-20 11:50:50.946: W/dalvikvm(23747): VFY: unable to resolve virtual method 11306: Ljavax/naming/Reference;.get (Ljava/lang/String;)Ljavax/naming/RefAddr;
03-20 11:50:50.946: D/dalvikvm(23747): VFY: replacing opcode 0x6e at 0x0004
03-20 11:50:50.946: W/dalvikvm(23747): VFY: unable to find class referenced in signature (Ljavax/naming/Reference;)
03-20 11:50:50.946: E/dalvikvm(23747): Could not find class 'javax.naming.StringRefAddr', referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.storeTo
03-20 11:50:50.946: W/dalvikvm(23747): VFY: unable to resolve new-instance 944 (Ljavax/naming/StringRefAddr;) in Lcom/mysql/jdbc/ConnectionPropertiesImpl$ConnectionProperty;
03-20 11:50:50.946: D/dalvikvm(23747): VFY: replacing opcode 0x22 at 0x0006
03-20 11:50:50.956: D/dalvikvm(23747): DexOpt: unable to opt direct call 0x2c2c at 0x14 in Lcom/mysql/jdbc/ConnectionPropertiesImpl$ConnectionProperty;.storeTo
03-20 11:50:51.146: E/SMD(330): DCD ON
03-20 11:50:51.476: I/dalvikvm(23747): Could not find method java.lang.management.ManagementFactory.getThreadMXBean, referenced from method com.mysql.jdbc.MysqlIO.appendDeadlockStatusInformation
03-20 11:50:51.476: W/dalvikvm(23747): VFY: unable to resolve static method 10657: Ljava/lang/management/ManagementFactory;.getThreadMXBean ()Ljava/lang/management/ThreadMXBean;
03-20 11:50:51.476: D/dalvikvm(23747): VFY: replacing opcode 0x71 at 0x0079
03-20 11:50:51.576: W/System.err(23747): com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
03-20 11:50:51.576: W/System.err(23747): The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
03-20 11:50:51.576: W/System.err(23747):    at java.lang.reflect.Constructor.constructNative(Native Method)
03-20 11:50:51.576: W/System.err(23747):    at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
03-20 11:50:51.576: W/System.err(23747):    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
03-20 11:50:51.586: W/System.err(23747):    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
03-20 11:50:51.586: W/System.err(23747):    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
03-20 11:50:51.586: W/System.err(23747):    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2332)
03-20 11:50:51.586: W/System.err(23747):    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2369)
03-20 11:50:51.586: W/System.err(23747):    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2153)
03-20 11:50:51.586: W/System.err(23747):    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
03-20 11:50:51.596: W/System.err(23747):    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
03-20 11:50:51.596: W/System.err(23747):    at java.lang.reflect.Constructor.constructNative(Native Method)
03-20 11:50:51.596: W/System.err(23747):    at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
03-20 11:50:51.596: W/System.err(23747):    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
03-20 11:50:51.596: W/System.err(23747):    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
03-20 11:50:51.596: W/System.err(23747):    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
03-20 11:50:51.606: W/System.err(23747):    at java.sql.DriverManager.getConnection(DriverManager.java:175)
03-20 11:50:51.606: W/System.err(23747):    at java.sql.DriverManager.getConnection(DriverManager.java:209)
03-20 11:50:51.606: W/System.err(23747):    at com.example.test_android.MainActivity.testDB(MainActivity.java:34)
03-20 11:50:51.606: W/System.err(23747):    at com.example.test_android.MainActivity.onCreate(MainActivity.java:24)
03-20 11:50:51.606: W/System.err(23747):    at android.app.Activity.performCreate(Activity.java:4470)
03-20 11:50:51.616: W/System.err(23747):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
03-20 11:50:51.616: W/System.err(23747):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
03-20 11:50:51.616: W/System.err(23747):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
03-20 11:50:51.616: W/System.err(23747):    at android.app.ActivityThread.access$600(ActivityThread.java:128)
03-20 11:50:51.616: W/System.err(23747):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
03-20 11:50:51.616: W/System.err(23747):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 11:50:51.626: W/System.err(23747):    at android.os.Looper.loop(Looper.java:137)
03-20 11:50:51.626: W/System.err(23747):    at android.app.ActivityThread.main(ActivityThread.java:4517)
03-20 11:50:51.626: W/System.err(23747):    at java.lang.reflect.Method.invokeNative(Native Method)
03-20 11:50:51.626: W/System.err(23747):    at java.lang.reflect.Method.invoke(Method.java:511)
03-20 11:50:51.626: W/System.err(23747):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
03-20 11:50:51.626: W/System.err(23747):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
03-20 11:50:51.636: W/System.err(23747):    at dalvik.system.NativeStart.main(Native Method)
03-20 11:50:51.636: W/System.err(23747): Caused by: java.net.SocketException: android.os.NetworkOnMainThreadException
03-20 11:50:51.636: W/System.err(23747):    at com.mysql.jdbc.StandardSocketFactory.unwrapExceptionToProperClassAndThrowIt(StandardSocketFactory.java:408)
03-20 11:50:51.636: W/System.err(23747):    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:269)
03-20 11:50:51.646: W/System.err(23747):    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:294)
03-20 11:50:51.646: W/System.err(23747):    ... 28 more
03-20 11:50:51.786: W/SurfaceFlinger(334): id=54502(1) createSurface 0x1b75144 (1x1),2 flag=400
03-20 11:50:51.786: D/KeyguardViewMediator(648): setHidden false
03-20 11:50:51.786: D/STATUSBAR-StatusBarManagerService(648): setSystemUiVisibility(0x0)
03-20 11:50:51.786: D/STATUSBAR-StatusBarManagerService(648): manageDisableList what=0x0 pkg=WindowManager.LayoutParams
03-20 11:50:51.867: D/CLIPBOARD(1073): Hide Clipboard dialog at Starting input: finished by someone else... !
03-20 11:50:51.867: I/ClipboardServiceEx(648): mCBPickerDialog enter case. MSG_DISMISS_DIALOG
03-20 11:50:51.867: I/ClipboardServiceEx(648): Send intent for dismiss clipboard dialog inside hideCurrentInputLocked() !

1 个答案:

答案 0 :(得分:2)

为什么它不在这里工作有两件事

jdbc无法点击您提供的URL,URL必须公开访问,这意味着您的服务器即:SAY x.y.z.w:port

所以需要一个网络人员来释放服务器ip上的这个端口并使其公开可用

<强>注意

公开打开这将导致您的数据库成为威胁,因为任何知道它的人都可以写入该数据库。

建议词 永远不要让你的应用程序直接与数据库通信,允许像jsp,servlets,asp,python等服务器技术接收你的请求并为你做。

我希望有所帮助。