14

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

Sujay
  • 6,753
  • 2
  • 30
  • 49
manuraphy
  • 143
  • 1
  • 1
  • 4

7 Answers7

13

You can't access a MySQL DB from Android natively. EDIT: Actually you may be able to use JDBC, but it is not recommended (or may not work?) ... see Android JDBC not working: ClassNotFoundException on driver

See

http://www.helloandroid.com/tutorials/connecting-mysql-database

http://www.basic4ppc.com/forum/basic4android-getting-started-tutorials/8339-connect-android-mysql-database-tutorial.html

Android cannot connect directly to the database server. Therefore we need to create a simple web service that will pass the requests to the database and will return the response.

http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html

For most [good] users this might be fine. But imagine you get a hacker that gets a hold of your program. I've decompiled my own applications and its scary what I've seen. What if they get your username / password to your database and wreak havoc? Bad.

Community
  • 1
  • 1
Jack
  • 9,156
  • 4
  • 50
  • 75
  • thankz for your quick reply jack. http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html – manuraphy Sep 02 '12 at 05:10
  • Hai jack i don't get some lines given in that blog mainly related to Ksop private static final String SOAP_ACTION = "http://ws.retailer.com/customerData"; private static final String METHOD_NAME = "customerData"; private static final String NAMESPACE = "http://ws.retailer.com/"; private static final String URL = "http://175.157.234.156:8085/ForBlog/services/RetailerWS?wsdl"; – manuraphy Sep 02 '12 at 05:35
  • 1
    "Android cannot connect directly to the database server" this sounds like a gospel. What are you actually promoting, a middleman (SOAP, REST, Web Services and other CORBA zombies)? – Tegiri Nenashi Feb 18 '14 at 01:49
  • 4
    I don't know how you can consider this an answer. You don't recommend JDBC which supports native drivers for databases. And then you don't support web services. So tell me, what's the use of this "answer"? – JohnMerlino May 31 '14 at 03:37
  • 4
    @JohnMerlino He didn't ask for a web service implementation and I'm not going to fully code one here. The question was "Connecting to MySQL from Android with JDBC". I did research and presented information. Please improve / edit / create your own answer if you feel you can do better. – Jack May 31 '14 at 17:48
  • I had the same problem, and referred to the first link in this answer to get a working solution. However, my app is a special case, targeting only my personal tablet and my own smartphone, being a small utility for my own online shop. (create orders and adjust stocks while selling something during the show, to prevent conflicts of online order for same items which I already sold for cash) – Petr Osipov Sep 09 '14 at 08:31
  • Say, when you are writing a MySQL client, this answer you are suggesting is very offensive to users' privacy. – SOFe Jul 07 '16 at 09:03
  • @Jack I imagine that if a hacker got hold of the source code, then no solution can help. Right ? Not just connecting to database directly. Any solution won't help. Agree ? – YoussefDir Oct 22 '20 at 09:47
4

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();
                    }
                }
            }
        }

    });


}
Ali
  • 41
  • 1
2

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.

Arun
  • 119
  • 1
  • 9
0

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.

Kamal
  • 5,462
  • 8
  • 45
  • 58
  • thank you kamal . i have seen many web service implementations in php . but i need a webservice in JSP because my server side is running in jsp script. . if u know something plz inform – manuraphy Sep 02 '12 at 05:29
  • Ofcourse you can create a web service using JSP. A web service is nothing but a web app which takes a request (string/XML) and returns a response (String/XML/JSON). You can easily do that in any language that supports Request/Response Architecture (including JSP). Though if you are looking for a proper documented, professional and reusable solution, you can use any tool like RESTEasy. – Kamal Sep 03 '12 at 05:42
0

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".

kaw
  • 77
  • 1
  • 4
0

try changing in the gradle file the targetSdkVersion to 8

targetSdkVersion 8
David Untama
  • 488
  • 3
  • 18
-1
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());
        }

    }