1. android中访问MySql数据库的代码:
package com.example.te;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String username;
String userpassword;
boolean flag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void connect(View view) throws ClassNotFoundException{
TextView textView = (TextView) findViewById(R.id.textView1);
try{
String url = \"jdbc:mysql://172.19.205.58:3306/test\";
Class.forName(\"com.mysql.jdbc.Driver\");
conn = DriverManager.getConnection(url, \"root\
ps=conn.prepareStatement(\"select * from jdbctest\");
rs = ps.executeQuery();
while(rs.next()){
username = rs.getString(2);
userpassword = rs.getString(3);
if(username.equals(\"luoxue\")){//判断用户名和密码是否正确
System.out.println(\"读取成功\");
textView.setText(username +\"密码\" + userpassword);
break;
}
}
}catch(SQLException e){
System.out.println(\"连接Mysql数据库失败!\");
// e.printStackTrace();
}finally{
close();
}
}
public void close(){
try {
if(rs!=null){
rs.close();
rs = null;
}
if(ps!=null){
ps.close();
ps = null;
}
if(conn!=null){
conn.close();
conn = null;
}
} catch (Exception e) {
System.out.println(\"数据库close异常\");
}
}
}
2.在AndroidManifest.xml中还要配置
具体如下:
................
3. 在使用Mysql数据库时要进行授权:
GRANT ALL PRIVILEGES ON *.* TO root@\"%\" IDENTIFIED BY '123456' WITH GRANT OPTION;
FLUSH PRIVILEGES;
4 . 还要注意ADT和SDK的版本,我的测试是在
android:minSdkVersion=\"8\"
android:targetSdkVersion=\"8\"
5. 实验图:
因篇幅问题不能全部显示,请点此查看更多更全内容