使用JDBC从Android连接到MySQL

man*_*phy 13 mysql android jdbc

我用下面的代码连接MySQLlocalhost从Android系统.它仅显示catch部分中给出的操作.我不知道是否是连接问题.

package com.test1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

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

public class Test1Activity extends Activity {
    /** Called when the activity is first created. */
    String str="new";
    static ResultSet rs;
    static PreparedStatement st;
    static Connection con;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final   TextView tv=(TextView)findViewById(R.id.user);

        try
        {
            Class.forName("com.mysql.jdbc.Driver");
              con=DriverManager.getConnection("jdbc:mysql://10.0.2.2:8080/example","root","");
            st=con.prepareStatement("select * from country where id=1");
            rs=st.executeQuery();
             while(rs.next())
             {
             str=rs.getString(2);


             }


            tv.setText(str);
            setContentView(tv);
        }
        catch(Exception e)
        {
            tv.setText(str);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当此代码执行时,它在avd中显示"new".

java.lang.management.ManagementFactory.getThreadMXBean, referenced from method com.mysql.jdbc.MysqlIO.appendDeadlockStatusInformation
Could not find class 'javax.naming.StringRefAddr', referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.storeTo
Could not find method javax.naming.Reference.get, referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.initializeFrom
Run Code Online (Sandbox Code Playgroud)

有谁能建议一些解决方案?并提前感谢

Jac*_*ack 13

您无法从本机访问Android的MySQL数据库.编辑:实际上你可能能够使用JDBC,但不建议(或者可能不起作用?)...请参阅Android JDBC无法正常工作:驱动程序上的ClassNotFoundException

看到

http://www.helloandroid.com/tutorials/connecting-mysql-database

http://www.basic4ppc.com/forum/basic4android-getting-started-tutorials/8339-connect-android-mysql-database-tutorial.html

Android无法直接连接到数据库服务器.因此,我们需要创建一个简单的Web服务,将请求传递给数据库并返回响应.

http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html

对于大多数[好]用户来说,这可能没问题.但想象一下,你会得到一个能够掌握你的程序的黑客.我已经反编译了我自己的应用程序,可怕的是我见过的.如果他们将您的用户名/密码输入您的数据库并造成严重破坏,该怎么办?坏.

  • 我不知道你怎么能考虑这个答案.您不建议使用支持数据库本机驱动程序的JDBC.然后你不支持Web服务.那么告诉我,这个"答案"的用途是什么? (4认同)
  • @JohnMerlino他没有要求Web服务实现,我不会在这里完全编写代码.问题是"使用JDBC从Android连接到MySQL".我做了研究并提供了信息.如果您觉得自己可以做得更好,请改进/编辑/创建自己的答案. (3认同)