英文:
Why do I have this error? MySQLNonTransientConnectionException
问题
我遇到了这个错误: >com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: 无法创建到数据库服务器的连接。
以下是我的代码:
public class MainActivity extends AppCompatActivity {
private static int SIGN_IN_CODE = 1;
private RelativeLayout activity_main;
private FloatingActionButton sendBtn;
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SIGN_IN_CODE) {
if (resultCode == RESULT_OK) {
Snackbar.make(activity_main, "您已成功登录!", Snackbar.LENGTH_LONG).show();
//displayAllMessages();
} else {
Snackbar.make(activity_main, "您未登录!", Snackbar.LENGTH_LONG).show();
finish();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main = findViewById(R.id.activity_main);
sendBtn = findViewById(R.id.btnSend);
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText textField = findViewById(R.id.messageField);
if (textField.getText().toString().equals(""))
return;
// SQL
//String connectionStr = "jdbc:mysql://109.95.210.183:3306/u86855_wp11";
String connectionStr = "jdbc:mysql://localhost:3306/app";
//String insert = "INSERT INTO u86855_wp11(nick, message) VALUES('lax','petro')";
String insert = "INSERT INTO users(nick, message) VALUES('lax','petro')";
try {
Object mysql = Class.forName("com.mysql.jdbc.Driver").newInstance();
//Connection dbConnection = DriverManager.getConnection(connectionStr,"u86855_wp11", "SchoolApp");
Connection dbConnection = DriverManager.getConnection(connectionStr, "SchoolApp", "SchoolApp");
Statement statement = dbConnection.createStatement();
ResultSet resultSet = statement.executeQuery(insert);
} catch (Exception e) {
textField.setText(e.toString());
Log.e("Error", "database", e);
}
// textField.setText("");
}
});
if (FirebaseAuth.getInstance().getCurrentUser() == null)
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE);
else {
Snackbar.make(activity_main, "您已成功登录!", Snackbar.LENGTH_LONG).show();
//displayAllMessages();
}
}
private void displayAllMessages() {
}
}
以下是我的错误日志:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: 无法创建到数据库服务器的连接。
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:403)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2266)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2015)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:768)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:403)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:385)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:323)
at java.sql.DriverManager.getConnection(DriverManager.java:569)
at java.sql.DriverManager.getConnection(DriverManager.java:219)
at com.example.databasetest.MainActivity$1.onClick(MainActivity.java:81)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:299)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2187)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2220)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2015)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:768)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:403)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:385)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:323)
at java.sql.DriverManager.getConnection(DriverManager.java:569)
at java.sql.DriverManager.getConnection(DriverManager.java:219)
at com.example.databasetest.MainActivity$1.onClick(MainActivity.java:81)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
英文:
I have this error: >com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
Here is my code:
public class MainActivity extends AppCompatActivity {
private static int SIGN_IN_CODE = 1;
private RelativeLayout activity_main;
private FloatingActionButton sendBtn;
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SIGN_IN_CODE) {
if (resultCode == RESULT_OK) {
Snackbar.make(activity_main, "Вы авторизованы!", Snackbar.LENGTH_LONG).show();
//displayAllMessages();
} else {
Snackbar.make(activity_main, "Вы не авторизованы!", Snackbar.LENGTH_LONG).show();
finish();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main = findViewById(R.id.activity_main);
sendBtn = findViewById(R.id.btnSend);
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText textField = findViewById(R.id.messageField);
if (textField.getText().toString().equals(""))
return;
//SQL
//String connectionStr = "jdbc:mysql://109.95.210.183:3306/u86855_wp11";
String connectionStr = "jdbc:mysql://localhost:3306/app";
//String insert = "INSERT INTO u86855_wp11(nick, message) VALUES('lax','petro')";
String insert = "INSERT INTO users(nick, message) VALUES('lax','petro')";
try {
Object mysql = Class.forName("com.mysql.jdbc.Driver").newInstance();
//Connection dbConnection = DriverManager.getConnection(connectionStr,"u86855_wp11", "SchoolApp");
Connection dbConnection = DriverManager.getConnection(connectionStr, "SchoolApp", "SchoolApp");
Statement statement = dbConnection.createStatement();
ResultSet resultSet = statement.executeQuery(insert);
} catch (Exception e) {
textField.setText(e.toString());
Log.e("Ошибка", "database", e);
}
// textField.setText("");
}
});
if (FirebaseAuth.getInstance().getCurrentUser() == null)
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE);
else {
Snackbar.make(activity_main, "Вы авторизованы!", Snackbar.LENGTH_LONG).show();
//displayAllMessages();
}
}
private void displayAllMessages() {
}
}
Here is my error Log:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:403)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2266)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2015)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:768)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:403)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:385)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:323)
at java.sql.DriverManager.getConnection(DriverManager.java:569)
at java.sql.DriverManager.getConnection(DriverManager.java:219)
at com.example.databasetest.MainActivity$1.onClick(MainActivity.java:81)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:299)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2187)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2220)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2015) 
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:768) 
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47) 
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:334) 
at com.mysql.jdbc.Util.handleNewInstance(Util.java:403) 
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:385) 
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:323) 
at java.sql.DriverManager.getConnection(DriverManager.java:569) 
at java.sql.DriverManager.getConnection(DriverManager.java:219) 
at com.example.databasetest.MainActivity$1.onClick(MainActivity.java:81) 
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
答案1
得分: 1
主要问题出现在您错误日志中的一行:
Caused by: android.os.NetworkOnMainThreadException
。
当您尝试在主线程上进行网络调用时,就会出现这个问题。您应该使用异步任务(AsyncTask)、RxJava或任何其他适当的方法来处理这个问题。
另一种方法是将以下代码粘贴到您的主活动(MainActivity)中,放在 setContentView
之后:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
并且在您的活动文件中导入以下内容:
import android.os.StrictMode;
英文:
The main issue is in the line
Caused by: android.os.NetworkOnMainThreadException
in your Error Log.
It happens when you try to make network call on main thread. You should be using Async task or Rxjava or any other approach for this.
Another approach can be paste this code in your main activity after setcontent view.
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
and import this in your activity file
import android.os.StrictMode;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论