0

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

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • "The Code seems right in my opinoin" - clearly that's not correct. The behavior you observe isn't desirable. Your code is the problem, not JDBC. – duffymo May 08 '19 at 18:21
  • Teach me please – Hein André May 08 '19 at 18:25
  • @duffymo it seems like Hein is new to StackOverflow, and may not be aware that when asking a question, helpful details are evidence of diagnosis over reassurances on what doesn't seem like a problem. Also, Hein, the goal here is to help you teach yourself and ensure your learnings are recorded in a high quality answer to your question, which could be discovered by future visitors. For more tips on what constitutes a great question, see https://stackoverflow.com/help/how-to-ask – ctt May 08 '19 at 18:28
  • @ctt thank you, and i really dont ve more details, the only thing i can add is, that i use github, and my partner has the same error. – Hein André May 08 '19 at 18:37
  • @HeinAndré "MySQLNonTransientConnectionException: Could not create connection to database server" did you double check your username/password? Is the DB really running? Can you connect with another tool to it? Is the port right? – Frieder May 08 '19 at 19:51

1 Answers1

1

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 (e.g. 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();
        }
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Thank you very much, it looks very clean, safety, and is easy to implement, but the error is still there, so like my guess, its not in the code, it is how i build my project/ libs etc. Someone can give me advice? – Hein André May 08 '19 at 19:15
  • No, it can't be the same error. The ResultSet in my code can never be null. Did you change the part of your code that is calling this new method? Did you rebuilt and repackage your app? – duffymo May 08 '19 at 19:17
  • Sorry for the confusion, the error which crash the run doesnt occur, but i still have problems with the MySQLNonTransientConnectionException – Hein André May 08 '19 at 19:40
  • Please be clearer. Popping your error message into Google brings this back. Check the version of the driver JAR: https://stackoverflow.com/questions/50177907/com-mysql-jdbc-exceptions-jdbc4-mysqlnontransientconnectionexception-could-not – duffymo May 08 '19 at 19:42
  • One more time: IT IS YOUR CODE. JDBC works - your code does not. – duffymo May 08 '19 at 19:45
  • MySQL Version 5.7.25 mysqlconnector 5.1.44 – Hein André May 08 '19 at 19:52
  • Sorry, I've done all I can for you. Check to make sure that those versions are compatible and correct. I'd advise that you strip this down to its essence and do the simplest thing possible: Can you connect to the database? If you can't do that, no sense it persisting. – duffymo May 08 '19 at 19:57
  • Yes, i cheked the connection beforehand with heidisql, the versions seems to be the problem, now i ve another error java.lang.BootstrapMethodError: Exception from call site #2 bootstrap method But i will saerch now again first for my self, may coming back here later – Hein André May 08 '19 at 20:07