Connecting to MariaDB from an Android app

5.9k Views Asked by At

Disclaimer: I know people don't typically do this, I am using an SQL database for cost reasons, also I am relatively new to programming.

I am trying to send SQL scripts to my MariaDB database from my Android Studio application. I am currently working to implement a Java Database Connectivity (JDBC) driver for MariaDB however I'm not sure what I need to include.

I went to the download website for the JDBC MariaDB driver however there are many jar files which I have the option of downloading. How do you know which one you need and how do you know how to install it/where for Android? (https://downloads.mariadb.org/connector-java/2.3.0/)

As a note, my Java code is as follows, for which I get the error message "No suitable driver found for .... ":

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null){
            if(result.getContents() == null) {
                Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_LONG).show();
            }
            else {
                // Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
                String host = "jdbc:mariadb://HOST:PORT/DBNAME";
                String username = "UNAME";
                String password ="PWD";
                try {
                    Connection con = DriverManager.getConnection( host, username, password );
                    Toast.makeText(this, result.getContents() + " - Success!", Toast.LENGTH_LONG).show();
                } catch (Exception err) {
                    Toast.makeText(this, err.getMessage(), Toast.LENGTH_LONG).show();

                }

            }
        }
        else {
            super.onActivityResult(requestCode, resultCode, data);
        }

    }
1

There are 1 best solutions below

0
Dave Enstrom On

You need to make sure to use the correct driver (connector). Download it and then you import it into Android Studio (libs folder) and then add the following to your app build gradle:

implementation files('libs/mariadb-java-client-1.8.0.jar')

This is the Connector/J that I use (V1.8.0) ... the newer ones don't seem to be compatible. Sample code:

// Create a connection 
val myConn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/DB?user=username&password=myPassword")
Class.forName("org.mariadb.jdbc.Driver")  // Initialize it

// Now you create SQL statements
val sql01 : PreparedStatement? = (myConn!!.prepareStatement(getString(R.string.sql01)))

// Submit the query
reset = sql01.executeQuery()