简体   繁体   中英

Added mysql-connector, but connection is still dying

I try to send query to my database in android studio, i managed this a few years back with eclipse, but now i want to code apps with this IDE

First i show you my code:

 private static int getAktuelleArtikelID() throws NumberFormatException, SQLException
    {
        ResultSet ergebnisSet = null;
        int ergebnis;
        try
        {
            Connection verbindung = DriverManager.getConnection("jdbc:mysql://localhost:3306/foo", "bar", "foobar!");
            Statement statement = verbindung.createStatement();
            String abfrage = "SELECT artikel_id FROM Artikel order by 1 desc limit 1";
            ergebnisSet = statement.executeQuery(abfrage);
            ergebnisSet.next();

        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }

        ergebnis = Integer.parseInt(ergebnisSet.getString(1));
        return ergebnis;

    }

The Code seems right in my opinoin, i rather have the problem with jdbc.

I added the mysqlconnector 5.1.44 like eplained here: Answer 2 from How to Mysql JDBC Driver to android studio

But i get this error:

W/System.err: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
W/System.err:     at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err:     at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
W/System.err:     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err:     at com.mysql.jdbc.Util.getInstance(Util.java:408)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2268)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2017)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
W/System.err:     at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
W/System.err:     at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err:     at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
W/System.err:     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
W/System.err:     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:569)
        at java.sql.DriverManager.getConnection(DriverManager.java:219)
W/System.err:     at com.example.androidcameraapi2.Database.getAktuelleArtikelID(Database.java:20)
W/System.err:     at com.example.androidcameraapi2.Database.artikelHochladen(Database.java:40)
W/System.err:     at com.example.androidcameraapi2.MainActivity$7.onClick(MainActivity.java:227)
W/System.err:     at android.view.View.performClick(View.java:6597)
W/System.err:     at android.view.View.performClickInternal(View.java:6574)
W/System.err:     at android.view.View.access$3100(View.java:778)
W/System.err:     at android.view.View$PerformClick.run(View.java:25885)
W/System.err:     at android.os.Handler.handleCallback(Handler.java:873)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err:     at android.os.Looper.loop(Looper.java:193)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6669)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)
W/System.err:     at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
        at java.net.InetAddress.getAllByName(InetAddress.java:1154)
W/System.err:     at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188)
        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2189)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2222)
W/System.err:   ... 24 more
D/AndroidRuntime: Shutting down VM

Also graddle wants an update, but i already tried it and it seems to make everything worse

Here are some suggestions:

  1. Never, ever pass a ResultSet out of method scope. You create it in a method and clean it up in that method. Load the data into objects and return those to the caller.
  2. Never, ever create a Connection in a data access class this way. You should be using pooled connections.
  3. Real applications log exceptions.
  4. Stick to SQL that isn't database specific (eg MySQL). You keep your code portable that way.
  5. If a value should be unique, build that requirement into your schema, not the query that fetches it.
  6. Connection parameters like URL, username, password should be externalized from your app in configuration.
  7. You should never use a database admin credential in an application.
  8. Plain text credentials are an invitation to break into your database.

Here's how I might write your method:

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * JDBC demo.
 * User: mduffy
 * Date: 5/8/19
 * Time: 2:37 PM
 * @link https://stackoverflow.com/questions/56046854/added-mysql-connector-but-connection-is-still-dying?noredirect=1#comment98735575_56046854
 */
public class JdbcDemo {

    private static final String SELECT_SQL = "SELECT artikel_id FROM Artikel ";

    private DataSource dataSource;

    public JdbcDemo(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public List<String> getAktuelleArtikelID() {
        List<String> aktuelleArtikelId = new ArrayList<>();
        ResultSet rs = null;
        Statement st = null;
        try {
            st = this.dataSource.getConnection().createStatement();
            rs = st.executeQuery(SELECT_SQL);
            while (rs.next()) {
                aktuelleArtikelId.add(rs.getString(1));
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(rs);
            close(st);
        }
        return aktuelleArtikelId;
    }

    // Should be in a utility class
    private static void close(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void close(Statement st) {
        try {
            if (st != null) {
                st.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM