您好,登錄后才能下訂單哦!
本篇內容主要講解“Android數據庫增刪改查的方法是什么”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Android數據庫增刪改查的方法是什么”吧!
頁面布局
代碼
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/tv_username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:layout_marginTop="10dp" android:text="用戶名:"/> <EditText android:id="@+id/et_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_toRightOf="@id/tv_username" android:minLines="2" /> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/et_username" android:layout_alignLeft="@id/et_username" android:layout_marginTop="10dp" android:inputType="textPassword" android:minLines="2" android:textSize="30sp" /> <TextView android:id="@+id/tv_choiceB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@id/et_password" android:textSize="30sp" android:text="密 碼:"/> <EditText android:id="@+id/et_age" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/et_password" android:layout_alignLeft="@id/et_password" android:layout_marginTop="10dp" android:minLines="2" /> <TextView android:id="@+id/tv_age" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@id/et_age" android:textSize="30sp" android:text="年 齡:"/> <Button android:id="@+id/bt_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/tv_age" android:layout_alignTop="@id/bt_query" android:text="保存" android:textSize="25sp" /> <Button android:id="@+id/bt_update" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="修改" android:layout_toRightOf="@id/bt_query" android:layout_below="@id/et_age" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:textSize="25sp" /> <Button android:id="@+id/bt_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="刪除" android:layout_toRightOf="@id/bt_update" android:layout_below="@id/et_age" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:textSize="25sp" /> <Button android:id="@+id/bt_query" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/et_age" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_toRightOf="@id/bt_save" android:text="查詢" android:textSize="25sp" /> <TextView android:id="@+id/tv_show" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/bt_save" android:textSize="25dp" /> </RelativeLayout>
通過點擊不同的按鈕,進行不同的增刪改查操作
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private SQLiteOpenHelper helper; private UserDao userDao; private User user; private EditText et_username,et_password,et_age; private Button bt_save,bt_query,bt_update,bt_delete; private TextView tv_show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化 init(); userDao=new UserDao(this); } public void init(){ et_username = findViewById(R.id.et_username); et_password = findViewById(R.id.et_password); et_age = findViewById(R.id.et_age); bt_save = findViewById(R.id.bt_save); bt_query = findViewById(R.id.bt_query); bt_update = findViewById(R.id.bt_update); bt_delete = findViewById(R.id.bt_delete); tv_show = findViewById(R.id.tv_show); bt_save.setOnClickListener(this); bt_query.setOnClickListener(this); bt_update.setOnClickListener(this); bt_delete.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.bt_save:{ user=new User(et_username.getText().toString(),et_password.getText().toString(),Integer.parseInt((et_age.getText().toString()))); long i=userDao.addUser(user); if(i!=-1){ Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(this, "添加失敗", Toast.LENGTH_SHORT).show(); } break; } case R.id.bt_delete:{ int i= userDao.deleteUser(et_username.getText().toString()); if(i!=0){ Toast.makeText(this, "刪除成功", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(this, "刪除失敗", Toast.LENGTH_SHORT).show(); } break; } case R.id.bt_update:{ user=new User(et_username.getText().toString(),et_password.getText().toString(),Integer.parseInt((et_age.getText().toString()))); int i= userDao.updateUser(user); if(i!=0){ Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(this, "修改失敗", Toast.LENGTH_SHORT).show(); } break; } case R.id.bt_query:{ //為了解決查詢重復問題,需要先創建一個StringBuffer或者String類型對象,用于存儲數據,存儲后在給控件賦值就可以解決 ArrayList list=userDao.queryAll(); StringBuffer buffer=new StringBuffer(); if(list.size()==0){ tv_show.setText("沒有數據"); }else { for (int i=0;i<list.size();i++){ User user= (User) list.get(i); buffer.append("id:" +user.getId()+ "用戶名:"+user.getUsername()+ "密碼:"+user.getPassword()+ "年齡:"+user.getAge()+"\n"); } tv_show.setText(buffer); } break; } } } }
包含對數據庫的增刪改查方法
public class UserDao { private SQLiteOpenHelper helper; public UserDao(Context context){ helper=new SQLiteOpenHelper(context,"user1",null,1); } //添加數據 public long addUser(User user){ //1.獲取數據庫對象 SQLiteDatabase database=helper.getWritableDatabase(); //那些列為空,可以設置為空 ContentValues values=new ContentValues(); //key是數據表的列名,value是要放進去的值 values.put("username",user.getUsername()); values.put("password",user.getPassword()); values.put("age",user.getAge()); //第一個參數表明,第二個參數自動賦值為null的列名,第三個參數數據 //返回值long,插入成功行號,插入失敗-1 long i=database.insert("users",null,values); //關閉數據庫 database.close(); return i; } //刪除 public int deleteUser(String username){ //1.獲取數據庫對象 SQLiteDatabase database=helper.getWritableDatabase(); //第一個參數表明,第二個參數為刪除條件,第三個參數為第二個參數中占位符所需值組成的字符串數組 int i=database.delete("users","username=?",new String[]{username+""}); //關閉數據庫 database.close(); return i; } //修改 public int updateUser(User user){ //1.獲取數據庫對象 SQLiteDatabase database=helper.getWritableDatabase(); //那些列為空,可以設置為空 ContentValues values=new ContentValues(); //key是數據表的列名,value是要放進去的值 values.put("username",user.getUsername()); values.put("password",user.getPassword()); values.put("age",user.getAge()); //第一個參數表明,第二個參數新數據,第三個參數是條件 int i=database.update("users",values,"username=?",new String[]{user.getUsername()}); //關閉數據庫 database.close(); return i; } //查詢 public ArrayList queryAll(){ ArrayList list=new ArrayList(); SQLiteDatabase database=helper.getWritableDatabase(); Cursor cursor=database.query("users",null,null,null,null,null,null); list=convertFromCursor(cursor); return list; } //通過對Cursor對象遍歷查詢結果,并將其范圍為一個list集合 private ArrayList convertFromCursor(Cursor cursor){ ArrayList list=new ArrayList(); if(cursor!=null&&cursor.moveToFirst()){ //通過游標遍歷這個集合 do{ int id=cursor.getInt(cursor.getColumnIndex("id")); String username=cursor.getString(cursor.getColumnIndex("username")); String password=cursor.getString(cursor.getColumnIndex("password")); int age=cursor.getInt(cursor.getColumnIndex("age")); User user=new User(id,username,password,age); list.add(user); }while (cursor.moveToNext()); } return list; } }
實體類對應著user表中的字段
public class User { private int id; private String username; private String password; private int age; public User(int id, String username, String password, int age) { this.id = id; this.username = username; this.password = password; this.age = age; } public User(String username, String password, int age) { this.username = username; this.password = password; this.age = age; } public User(){}; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
創建表,更新表方法
public class SQLiteOpenHelper extends android.database.sqlite.SQLiteOpenHelper { private Context context; public static final String CREATE_TABLES="create table users ("+ "id integer primary key autoincrement,"+ "username text,"+ "password text,"+ "age integer)"; public static final String CREATE_DEPARTMENT="create table department ("+ "id integer primary key autoincrement,"+ "departmentName text,"+ "departCode text)"; public SQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); this.context=context; } //創建數據表(只有在第一次創建數據庫的時候才會被調用) @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(CREATE_TABLES); Toast.makeText(context, "success databases", Toast.LENGTH_SHORT).show(); } //數據庫的更新(第一個參數數據庫對象,第二個參數舊版本號,第三個參數新版本號) //新版本號大于舊版本號就會調用onUpgrade方法 @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { /** * //如果數據表存在就刪除 * sqLiteDatabase.execSQL("drop table if exists users"); * sqLiteDatabase.execSQL("drop table if exists department"); * onCreate(sqLiteDatabase); */ switch (i){ case 1:sqLiteDatabase.execSQL(CREATE_DEPARTMENT); } } }
到此,相信大家對“Android數據庫增刪改查的方法是什么”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。