Android连接Mysql数据库

package com.hl;

import java.sql.DriverManager;
import java.sql.ResultSet;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class AndroidMsql extends Activity {

	private Connection conn;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button btn = (Button) findViewById(R.id.btn);
		sqlCon();
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				queryData();
			}
		});

	}

	private void mSetText(String str) {
		TextView txt = (TextView) findViewById(R.id.txt);
		txt.setText(str);
	}

	private void queryData() {

		Statement stmt;
		try {
			stmt = (Statement) conn
					.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
							ResultSet.CONCUR_UPDATABLE);
			String sql = "select * from user";// 查询user表语句
			ResultSet rs = stmt.executeQuery(sql);// 执行查询
			StringBuilder str = new StringBuilder();
			while (rs.next()) {
				str.append(rs.getString(2) + "\n");
			}
			mSetText(str.toString());

			rs.close();
			stmt.close();
			conn.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void sqlCon() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			
			String url = "jdbc:mysql://***.**.**.**:3306/test?user=root&password=root&useUnicode=true&characterEncoding=UTF-8";// 链接数据库语句

			conn = (Connection) DriverManager.getConnection(url); // 链接数据库
			// Statement stmt=(Statement)
			// conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

			// String sql="select * from user";//查询user表语句
			// ResultSet rs=stmt.executeQuery(sql);//执行查询
			// StringBuilder str=new StringBuilder();
			// while(rs.next()){
			// str.append(rs.getString(2)+"\n");
			// }
			// mSetText(str.toString());
			//
			// rs.close();
			// stmt.close();
			// conn.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

相关推荐