SQLite数据库存储(下)
1.增添数据
对于添加数据的话我们只需要在主活动当中import新的包以及在主活动当中写上适当的代码就可以了,不需要在我们之前创建新的类当中书写新的代码。现在的主活动代码如下:
package com.example.lenovo.studyittwo; import android.content.IntentFilter; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.content.*; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private MyDatabaseHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 构建MyDatabaseHelper对象,指定数据库名为"BookStore.db、版本号为1,版本号改为2之后则会直接 dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2); Button btn_create_database = (Button) findViewById(R.id.creat); btn_create_database.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 创建或打开一个现有的数据库(已存在则打开,否则创建一个新的) dbHelper.getWritableDatabase(); } }); Button addData= (Button)findViewById(R.id.add); addData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SQLiteDatabase db=dbHelper.getWritableDatabase(); ContentValues values=new ContentValues(); values.put("name","the fuck code"); values.put("autuor","fuckers"); db.insert("Book",null,values); values.clear(); values.put("name","the fuck code"); values.put("autuor","fuckers"); db.insert("Category",null,values); values.clear(); } }); }}
这样我们就分别向book表以及category表当中增添了数据了。当然我们也可以在这段代码当中看到我们新建了一个按钮,用于演示我们数据是否已经插入成功,下面是我们新的主活动界面的代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/creat" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Create database"/> <Button android:id="@+id/add" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Add data"/> </LinearLayout>
很自然地运用了一个线性的垂直布局,只是增加了一个button而已。
2.更改数据
为了方便研究更改数据,我们在布局下加入更改数据的按钮,代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="h