mysql-connector-java-5.1.10-bin.jar
をビルドパスに追加
sampleActivity.java
package mysql.jp;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class sampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
//データベースに接続
Connection con = MySqlConnect.getConnection();
//ステートメントオブジェクトを作成
Statement stmt = (Statement) con.createStatement();
//SQL
String mySql = "select date from table;";
ResultSet rs = stmt.executeQuery(mySql);
while(rs.next()) {
Toast.makeText(getApplicationContext(), rs.getString("date"), Toast.LENGTH_LONG).show();
}
//オブジェクトを解放
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
}
}
}
MySqlConnect.java
package mysql.jp;
import java.sql.*;
class MySqlConnect{
static Connection getConnection() throws Exception {
//JDBCドライバのロード
Class.forName("com.mysql.jdbc.Driver");
//各設定
String url = "jdbc:mysql://xxx.xxx.xxx.xxx/db_name";
String user = "user_name";
String pass = "password";
//データベースに接続
Connection con = DriverManager.getConnection(url,user,pass);
return con;
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>