使用 JDBC 从 Android 连接到 MySQL [英] Connecting to MySQL from Android with JDBC
问题描述
我使用以下代码从 Android 连接 localhost
中的 MySQL
.它只显示 catch 部分中给出的操作.不知道是不是连接问题.
I used the following code to connect MySQL
in localhost
from Android. It only displays the actions given in catch section . I do not know whether it is a connection problem or not.
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 中显示new".
When this code executes it displays "new" in the 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
谁能提出一些解决方案?并提前致谢
Can anyone suggest some solution? And thanks in advance
推荐答案
您无法从 Android 本地访问 MySQL 数据库.实际上您可以使用 JDBC,但不推荐使用(或可能不起作用?)...请参阅 Android JDBC 不工作:驱动程序上的 ClassNotFoundException
You can't access a MySQL DB from Android natively. Actually you may be able to use JDBC, but it is not recommended (or may not work?) ... see Android JDBC not working: ClassNotFoundException on driver
见
http://www.helloandroid.com/tutorials/connecting-mysql-database
Android 无法直接连接到数据库服务器.因此我们需要创建一个简单的 Web 服务,将请求传递给数据库并将返回响应.
Android cannot connect directly to the database server. Therefore we need to create a simple web service that will pass the requests to the database and will return the response.
http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html
对于大多数 [good] 用户来说,这可能没问题.但是想象一下,你有一个黑客控制了你的程序.我已经反编译了我自己的应用程序,并且看到了可怕的东西.如果他们将您的用户名/密码获取到您的数据库并造成严重破坏怎么办?不好.
For most [good] users this might be fine. But imagine you get a hacker that gets a hold of your program. I've decompiled my own applications and its scary what I've seen. What if they get your username / password to your database and wreak havoc? Bad.
这篇关于使用 JDBC 从 Android 连接到 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!