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(); } } }
相关推荐
CoderToy 2020-11-16
技术之博大精深 2020-10-16
emmm00 2020-11-17
bianruifeng 2020-11-16
云中舞步 2020-11-12
世樹 2020-11-11
暗夜之城 2020-11-11
张荣珍 2020-11-12
amienshxq 2020-11-14
ASoc 2020-11-14
yungpheng 2020-10-19
loveyouluobin 2020-09-29
尘封飞扬 2020-09-29
Coder技术文摘 2020-09-29
lbyd0 2020-11-17
BigYellow 2020-11-16
sushuanglei 2020-11-12
我心似明月 2020-11-09