[英]Code in Eclipse works, but doesn't work on Android
I have this problem for about 2 days and I cannot find any solution. 我有这个问题大约2天,找不到任何解决方案。 Thing is I'm using MySQL-Connection-Java to operate MySQL base on Android. 我正在使用MySQL-Connection-Java在Android上运行MySQL。 While debugging it cannot connect with this base, even though code in Eclipse Java works fine. 在调试时,即使Eclipse Java中的代码工作正常,它也不能与此基础连接。 I was looking throughout many forum discussions on the Internet, but seems like there is no valid solution, or maybe I am THAT blind. 我在Internet上浏览了很多论坛讨论,但似乎没有有效的解决方案,或者我似乎是盲目的。 Below you can see class code that I'm using. 在下面,您可以看到我正在使用的类代码。 I have no clue why in Eclipse in connects with the base, but on the Android device it doesn't want to. 我不知道为什么在Eclipse中与基础连接,但是在Android设备上却不希望如此。
Error code:com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. 错误代码:com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:无法创建与数据库服务器的连接。 Attempted reconnect 3 times. 尝试重新连接3次。 Giving up. 放弃。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JDBC {
// init database constants
private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
private stat
ic final String DATABASE_URL = "jdbc:mysql://sql7.freemysqlhosting.net/sql7109625?autoReconnect=true";
private static final String USERNAME = "REMOVED";
private static final String PASSWORD = "REMOVED";
private static final String MAX_POOL = "250";
// init connection object
private Connection connection;
// init properties object
private Properties properties;
// create properties
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
// connect database
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return connection;
}
// disconnect database
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
} }
I find my problem. 我发现我的问题。 I use 我用
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
and my application work :) 和我的申请工作:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.