使用 JDBC 从 Android 连接到 MySQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12233145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Connecting to MySQL from Android with JDBC
提问by manuraphy
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.
我用下面的代码连接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);
}
}
}
When this code executes it displays "new" in the avd.
当此代码执行时,它会在 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
Can anyone suggest some solution? And thanks in advance
任何人都可以提出一些解决方案吗?并提前致谢
采纳答案by Hyman
You can't access a MySQL DB from Android natively. EDIT: 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
您无法从 Android 本地访问 MySQL 数据库。编辑:实际上您可以使用 JDBC,但不推荐(或可能不起作用?)...请参阅Android JDBC 不工作:驱动程序上的 ClassNotFoundException
See
看
http://www.helloandroid.com/tutorials/connecting-mysql-database
http://www.helloandroid.com/tutorials/connecting-mysql-database
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.
Android 无法直接连接到数据库服务器。因此,我们需要创建一个简单的 Web 服务,它将请求传递到数据库并返回响应。
http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html
http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html
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.
对于大多数[好]用户来说,这可能没问题。但是想象一下,你有一个黑客控制了你的程序。我已经反编译了我自己的应用程序,并且看到了可怕的东西。如果他们将您的用户名/密码获取到您的数据库并造成严重破坏怎么办?坏的。
回答by Ali
this code runs permanently!!! created by diko(Turkey)
此代码永久运行!!!由 diko(土耳其)创建
public void mysql() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
thrd1 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
if (con == null) {
try {
con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
} catch (SQLException e) {
e.printStackTrace();
con = null;
}
if ((thrd2 != null) && (!thrd2.isAlive()))
thrd2.start();
}
}
}
});
if ((thrd1 != null) && (!thrd1.isAlive())) thrd1.start();
thrd2 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
if (con != null) {
try {
// con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
Statement st = con.createStatement();
String ali = "'fff'";
st.execute("INSERT INTO deneme (name) VALUES(" + ali + ")");
// ResultSet rs = st.executeQuery("select * from deneme");
// ResultSetMetaData rsmd = rs.getMetaData();
// String result = new String();
// while (rs.next()) {
// result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
// result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
// }
} catch (SQLException e) {
e.printStackTrace();
con = null;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
}
回答by Arun
If u need to connect your application to a server you can do it through PHP/MySQL and JSON http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/.Mysql Connection code should be in AsynTask class. Dont run it in Main Thread.
如果您需要将您的应用程序连接到服务器,您可以通过 PHP/MySQL 和 JSON http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/.Mysql连接代码应该在 AsynTask 类中。不要在主线程中运行它。
回答by user3252230
public void testDB() {
TextView tv = (TextView) this.findViewById(R.id.tv_data);
try {
Class.forName("com.mysql.jdbc.Driver");
// perfect
// localhost
/*
* Connection con = DriverManager .getConnection(
* "jdbc:mysql://192.168.1.5:3306/databasename?user=root&password=123"
* );
*/
// online testing
Connection con = DriverManager
.getConnection("jdbc:mysql://173.5.128.104:3306/vokyak_heyou?user=viowryk_hiweser&password=123");
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from tablename ");
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
result += rsmd.getColumnName(1) + ": " + rs.getString(1) + "\n";
}
tv.setText(result);
} catch (Exception e) {
e.printStackTrace();
tv.setText(e.toString());
}
}
回答by David Untama
try changing in the gradle file the targetSdkVersion to 8
尝试在 gradle 文件中将 targetSdkVersion 更改为 8
targetSdkVersion 8
回答by Kamal
Do you want to keep your database on mobile? Use sqlite instead of mysql.
您想将数据库保留在移动设备上吗?使用 sqlite 而不是 mysql。
If the idea is to keep database on server and access from mobile. Use a webservice to fetch/ modify data.
如果想法是将数据库保留在服务器上并从移动设备访问。使用网络服务来获取/修改数据。
回答by kaw
An other approach is to use a Virtual JDBC Driver that uses a three-tier architecture: your JDBC code is sent through HTTP to a remote Servlet that filters the JDBC code (configuration & security) before passing it to the MySql JDBC Driver. The result is sent you back through HTTP. There are some free software that use this technique. Just Google "Android JDBC Driver over HTTP".
另一种方法是使用使用三层架构的虚拟 JDBC 驱动程序:您的 JDBC 代码通过 HTTP 发送到远程 Servlet,该 Servlet 过滤 JDBC 代码(配置和安全性),然后再将其传递给 MySql JDBC 驱动程序。结果通过 HTTP 发回给您。有一些免费软件使用了这种技术。只是谷歌“Android JDBC Driver over HTTP”。