为什么会出现这个错误?MySQLNonTransientConnectionException

huangapple go评论76阅读模式
英文:

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, &quot;Вы авторизованы!&quot;, Snackbar.LENGTH_LONG).show();
//displayAllMessages();
} else {
Snackbar.make(activity_main, &quot;Вы не авторизованы!&quot;, 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(&quot;&quot;))
return;
//SQL
//String connectionStr = &quot;jdbc:mysql://109.95.210.183:3306/u86855_wp11&quot;;
String connectionStr = &quot;jdbc:mysql://localhost:3306/app&quot;;
//String insert = &quot;INSERT INTO u86855_wp11(nick, message) VALUES(&#39;lax&#39;,&#39;petro&#39;)&quot;;
String insert = &quot;INSERT INTO users(nick, message) VALUES(&#39;lax&#39;,&#39;petro&#39;)&quot;;
try {
Object mysql = Class.forName(&quot;com.mysql.jdbc.Driver&quot;).newInstance();
//Connection dbConnection = DriverManager.getConnection(connectionStr,&quot;u86855_wp11&quot;, &quot;SchoolApp&quot;);
Connection dbConnection = DriverManager.getConnection(connectionStr, &quot;SchoolApp&quot;, &quot;SchoolApp&quot;);
Statement statement = dbConnection.createStatement();
ResultSet resultSet = statement.executeQuery(insert);
} catch (Exception e) {
textField.setText(e.toString());
Log.e(&quot;Ошибка&quot;, &quot;database&quot;, e);
}
// textField.setText(&quot;&quot;);
}
});
if (FirebaseAuth.getInstance().getCurrentUser() == null)
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE);
else {
Snackbar.make(activity_main, &quot;Вы авторизованы!&quot;, 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.&lt;init&gt;(ConnectionImpl.java:768)
at com.mysql.jdbc.JDBC4Connection.&lt;init&gt;(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.&lt;init&gt;(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)&#160;
at com.mysql.jdbc.ConnectionImpl.&lt;init&gt;(ConnectionImpl.java:768)&#160;
at com.mysql.jdbc.JDBC4Connection.&lt;init&gt;(JDBC4Connection.java:47)&#160;
at java.lang.reflect.Constructor.newInstance0(Native Method)&#160;
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)&#160;
at com.mysql.jdbc.Util.handleNewInstance(Util.java:403)&#160;
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:385)&#160;
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:323)&#160;
at java.sql.DriverManager.getConnection(DriverManager.java:569)&#160;
at java.sql.DriverManager.getConnection(DriverManager.java:219)&#160;
at com.example.databasetest.MainActivity$1.onClick(MainActivity.java:81)&#160;
at android.view.View.performClick(View.java:6256)&#160;
at android.view.View$PerformClick.run(View.java:24701)&#160;
at android.os.Handler.handleCallback(Handler.java:789)&#160;
at android.os.Handler.dispatchMessage(Handler.java:98)&#160;
at android.os.Looper.loop(Looper.java:164)&#160;
at android.app.ActivityThread.main(ActivityThread.java:6541)&#160;
at java.lang.reflect.Method.invoke(Native Method)&#160;
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)&#160;
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)&#160;

答案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 &gt; 9) {
StrictMode.ThreadPolicy policy = new 
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

and import this in your activity file

import android.os.StrictMode;

huangapple
  • 本文由 发表于 2020年8月16日 01:04:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63428697.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定