Android Studio + sqllite 数据库连接的步骤以及常见问题
软件见文末
一、连接步骤
前提是先安装好sqllite---->无脑式next安装
1、打开Android studio 创建一对Activity,
2、书写相关代码
// 在 StudentActivity.java
package com.example.myapplication01;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class StudentActivity extends AppCompatActivity {
private EditText bianhao;
private EditText name;
private EditText age;
private EditText czbianhao;
private EditText czname;
private TextView czresult;
private SQLiteDatabase database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student);
bianhao = findViewById(R.id.bianhao);
name = findViewById(R.id.name);
age = findViewById(R.id.age);
czbianhao = findViewById(R.id.czbianhao);
czname = findViewById(R.id.czxingming);
czresult = findViewById(R.id.result);
Mydatabase mydatabase = new Mydatabase(StudentActivity.this);
database = mydatabase.getWritableDatabase();
}
public void insert(View view) {
String sql1 = "select * from user where 编号=?";
Cursor cursor = database.rawQuery(sql1, new String[]{
bianhao.getText().toString()});
if (cursor.getCount() == 0) {
String sql = "insert into user(编号,姓名,年龄)values(?,?,?)";
database.execSQL(sql, new Object[]{
Integer.parseInt(bianhao.getText().toString()), name.getText().toString(),
Integer.parseInt(age.getText().toString())});
Toast.makeText(getApplicationContext(), "已成功添加!!!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "数据已存在!!!", Toast.LENGTH_SHORT).show();
bianhao.setText("");
bianhao.requestFocus();
}
}
//方法二
/*String sql1="select * from user where 编号=?";
Cursor cursor = database.rawQuery(sql1,new String[]{bianhao.getText().toString()});
if(cursor.getCount()==0){
ContentValues contentValues = new ContentValues();
contentValues.put("编号",Integer.parseInt(bianhao.getText().toString()));
contentValues.put("姓名",name.getText().toString());
contentValues.put("年龄",Integer.parseInt(age.getText().toString()));
Toast.makeText(getApplicationContext(),"已成功添加!!!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"数据已存在!!!",Toast.LENGTH_SHORT).show();
bianhao.setText("");
bianhao.requestFocus();
}*/
public void delete(View view){
String sql = "delete from user where 编号=?";
database.execSQL(sql,new Object[]{
Integer.parseInt(bianhao.getText().toString())});
Toast.makeText(getApplicationContext(),"数据已删除!!!",Toast.LENGTH_SHORT).show();
}
public void update(View view){
String sql = "update user set 姓名=?,年龄=? where 编号=?";
database.execSQL(sql,new Object[]{
name.getText().toString(),Integer.parseInt(age.getText().toString()),
Integer.parseInt(bianhao.getText().toString())});
Toast.makeText(getApplicationContext(),"数据已更新!!!",Toast.