in the last 2-3 days i've search a solution to connect my android app to a mysql server directly and i found the right way to do this in java.
this is what i did:
- create new android project on eclipse
- import in my referenced library the jar file linked below (mysql-connector-java.jar) that is part of libmysql-java linux packet
- add the instruction "import java.sql.*" to use the library mentioned above
i've created a database with one table with 2 fields, id and data.
in the example below i've opened a connection to mysql server and execute a query "select * from table_name".
all works fine.
mr. erel, can you implement a mysql library with this?
package com.android.mysql;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Button;
import java.sql.*;
public class AndMysqlActivity extends Activity {
/** Called when the activity is first created. */
private static final String url = "jdbc:mysql://mysql-server/db_name";
private static final String user = "username";
private static final String pass = "password";
private Integer c = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* setContentView(R.layout.main); */
dbconn();
}
public void dbconn() {
TextView tv1 = new TextView(this);
Button b1 = new Button(this);
String testo;
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
/* System.out.println("Database connection success"); */
tv1.setText("Database connection success");
ll.addView(tv1);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from table_name");
while(rs.next()) {
testo = "Id: " + rs.getInt(1);
tv1 = new TextView(this);
tv1.setText(testo);
ll.addView(tv1);
testo = "Data: " + rs.getString(2);
tv1 = new TextView(this);
tv1.setText(testo);
ll.addView(tv1);
/*System.out.println("Id " + rs.getInt(1));
System.out.println("Data " + rs.getString(2));
System.out.println("");*/
}
}
catch(Exception e) {
/* e.printStackTrace(); */
tv1 = new TextView(this);
tv1.setText(e.toString());
ll.addView(tv1);
}
b1.setText("Reload " + c++);
b1.setGravity(Gravity.CENTER);
b1.setClickable(true);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View viewParam) {
dbconn();
}
});
ll.addView(b1);
this.setContentView(ll);
}
}
mysql-connector-java.jar -
link