MySql驱动类下载地址:链接: https://pan.baidu.com/s/1KiLGcR7CgIVt7TES7sugkQ 密码: k70o
下载完成将connect这个类放到android工程目录Lib文件夹下
然后右键单击选择Add AS Lib 就算是完成添加依赖了。
连接数据库:
在全局变量中定义一个动态加载类
private static String driver ="com.mysql.jdbc.Driver";
和conn连接状态
public static Connection connection =null;
通过 DriverManager.getConnection 连接数据库
注意:要在子线程中操作
public void Connect() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Class.forName(driver);// 动态加载类
connection = DriverManager.getConnection("jdbc:mysql://数据库IP/数据库名?useUnicode=true&characterEncoding=utf8","账号","密码");
Log.d(String.valueOf(this),"连接数据库crate");
Looper.prepare();
Toast.makeText(MainActivity.this,"连接成功",Toast.LENGTH_SHORT).show();
Looper.loop();
}catch (SQLException | ClassNotFoundException e) {
Log.d(String.valueOf(this),"连接数据库异常:"+e.toString());
Toast.makeText(MainActivity.this,"连接失败",Toast.LENGTH_SHORT).show();
}
}
}).start();
}
这里连接成功了会在上面全局变量中的connection中保存连接的状态
二、数据查询
public void mQuery(){
final String SQL ="select *from user";
final String[] ID = {null};
new Thread(new Runnable() {
@Override
public void run() {
try {
Statement statement = (Statement)connection.createStatement();
ResultSet resultSet = statement.executeQuery(SQL);
while (resultSet.next()){
ID[0] = resultSet.getString("ID");
}
Log.d(String.valueOf(this),"数据库的数据:"+ID[0]);
Looper.prepare();
Toast.makeText(MainActivity.this,ID[0],Toast.LENGTH_SHORT).show();
Looper.loop();
}catch (SQLException e) {
e.printStackTrace();
}
}
}).start();
}
三、数据添加
public void addTable(){
new Thread(new Runnable() {
@Override
public void run() {
String SQL ="insert into user values('val','val');";
try {
Statement statement =connection.createStatement();
statement.execute(SQL);
}catch (SQLException e) {
Log.d(String.valueOf(this),"写入失败"+e.toString());
}
}
}).start();
}
四、数据修改
public void Edit(){
final String SQL ="update user set PWD = '1234' where ID = '123';";
new Thread(new Runnable() {
@Override
public void run() {
try{
Statement statement =connection.createStatement();
statement.executeUpdate(SQL);
}catch (Exception e){
Log.d(String.valueOf(this),"修改失败"+e.toString());
}
}
}).start();
}
五、数据删除
public void del(){
final String SQL ="delete from user where ID = '122232';";
new Thread(new Runnable() {
@Override
public void run() {
try {
Statement statement =connection.createStatement();
statement.execute(SQL);
}catch (SQLException e) {
Log.d(String.valueOf(this),"删除失败"+e.toString());
}
}
}).start();
}
断开数据库用:
connection.close();
——出处:唐瀚林
挥舞着键盘和本子,将这世界写个明白。