开发者社区> 问答> 正文

使用JDBC从Android连接到MySQL

我用下面的代码连接MySQL在localhost从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);
    }
}

} 执行此代码后,它将在avd中显示“新”。

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 谁能提出一些解决方案?并预先感谢

展开
收起
保持可爱mmm 2020-05-11 16:01:32 493 0
1 条回答
写回答
取消 提交回答
  • 您无法从本机访问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

    对于大多数[好]用户来说,这可能很好。但是,想象一下您拥有一个掌握了程序的黑客。我已经对自己的应用程序进行了反编译,并且看到的结果令人恐惧。如果他们将您的用户名/密码发送到数据库并造成严重破坏该怎么办?坏。来源:stack overflow

    2020-05-11 16:01:45
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载

相关镜像