[android] Connecting to MySQL from Android with JDBC

I used the following code to connect MySQL in localhost from Android. It only displays the actions given in catch section . I do not know whether it is a connection problem or not.

package com.test1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test1Activity extends Activity {
    /** Called when the activity is first created. */
    String str="new";
    static ResultSet rs;
    static PreparedStatement st;
    static Connection con;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final   TextView tv=(TextView)findViewById(R.id.user);

        try
        {
            Class.forName("com.mysql.jdbc.Driver");
              con=DriverManager.getConnection("jdbc:mysql://10.0.2.2:8080/example","root","");
            st=con.prepareStatement("select * from country where id=1");
            rs=st.executeQuery();
             while(rs.next())
             {
             str=rs.getString(2);


             }


            tv.setText(str);
            setContentView(tv);
        }
        catch(Exception e)
        {
            tv.setText(str);
        }
    }
}

When this code executes it displays "new" in the avd.

java.lang.management.ManagementFactory.getThreadMXBean, referenced from method com.mysql.jdbc.MysqlIO.appendDeadlockStatusInformation
Could not find class 'javax.naming.StringRefAddr', referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.storeTo
Could not find method javax.naming.Reference.get, referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.initializeFrom

Can anyone suggest some solution? And thanks in advance

This question is related to android mysql jdbc

The answer is


try changing in the gradle file the targetSdkVersion to 8

targetSdkVersion 8

Do you want to keep your database on mobile? Use sqlite instead of mysql.

If the idea is to keep database on server and access from mobile. Use a webservice to fetch/ modify data.


public void testDB() {
        TextView tv = (TextView) this.findViewById(R.id.tv_data);
        try {

            Class.forName("com.mysql.jdbc.Driver");

            // perfect

            // localhost

            /*
             * Connection con = DriverManager .getConnection(
             * "jdbc:mysql://192.168.1.5:3306/databasename?user=root&password=123"
             * );
             */

            // online testing

            Connection con = DriverManager
                    .getConnection("jdbc:mysql://173.5.128.104:3306/vokyak_heyou?user=viowryk_hiweser&password=123");

            String result = "Database connection success\n";
            Statement st = con.createStatement();

            ResultSet rs = st.executeQuery("select * from tablename ");
            ResultSetMetaData rsmd = rs.getMetaData();

            while (rs.next()) {

                result += rsmd.getColumnName(1) + ": " + rs.getString(1) + "\n";

            }
            tv.setText(result);
        } catch (Exception e) {
            e.printStackTrace();
            tv.setText(e.toString());
        }

    }

this code runs permanently!!! created by diko(Turkey)

public void mysql() {

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();

    }

    thrd1 = new Thread(new Runnable() {
        public void run() {
            while (!Thread.interrupted()) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e1) {

                }
                if (con == null) {
                    try {
                        con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");

                    } catch (SQLException e) {
                        e.printStackTrace();
                        con = null;
                    }

                    if ((thrd2 != null) && (!thrd2.isAlive()))
                        thrd2.start();

                }
            }

        }
    });
    if ((thrd1 != null) && (!thrd1.isAlive())) thrd1.start();

    thrd2 = new Thread(new Runnable() {
        public void run() {
            while (!Thread.interrupted()) {

                if (con != null) {
                    try {
                     //   con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
                        Statement st = con.createStatement();
                        String ali = "'fff'";
                        st.execute("INSERT INTO deneme (name) VALUES(" + ali + ")");
                      //  ResultSet rs = st.executeQuery("select * from deneme");
                      //  ResultSetMetaData rsmd = rs.getMetaData();
                      //  String result = new String();


                      //  while (rs.next()) {
                      //      result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
                     //       result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";


                     //   }

                    } catch (SQLException e) {
                        e.printStackTrace();
                        con = null;
                    }

                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    });


}

If u need to connect your application to a server you can do it through PHP/MySQL and JSON http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ .Mysql Connection code should be in AsynTask class. Dont run it in Main Thread.


An other approach is to use a Virtual JDBC Driver that uses a three-tier architecture: your JDBC code is sent through HTTP to a remote Servlet that filters the JDBC code (configuration & security) before passing it to the MySql JDBC Driver. The result is sent you back through HTTP. There are some free software that use this technique. Just Google "Android JDBC Driver over HTTP".


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to jdbc

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' Hibernate Error executing DDL via JDBC Statement Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] MySQL JDBC Driver 5.1.33 - Time Zone Issue Spring-Boot: How do I set JDBC pool properties like maximum number of connections? Where can I download mysql jdbc jar from? Print the data in ResultSet along with column names How to set up datasource with Spring for HikariCP? java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why? java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname