30
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

android⇒外部mysql接続

Posted at

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>
30
30
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?