SQLite数据库增删改查

    SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它是D.RichardHipp建立的公有领域项目。它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源的世界著名数据库管理系统来讲,它的处理速度比他们都快。SQLite第一个Alpha版本诞生于2000年5月。 至2018年已经有18个年头



布局文件activity_main.xml

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.databaseoperate.MainActivity">


    <Button
        android:id="@+id/create_database"
        android:text="点击我将会为你创建数据库"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/insertdata"
        android:text="点击我插入书籍"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/deletedata"
        android:text="点击我删除数据"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/updatedata"
        android:text="点击我更新数据"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/query"
        android:text="点击我查询数据"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/showContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


</LinearLayout>




数据库文件MyDatabaseHelper.java

package com.example.databaseoperate;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;


/**
 * 创建数据库,必须继承SQLiteOpenHelper
 */


public class MyDatabaseHelper extends SQLiteOpenHelper {
    //创建一本书的表
    public static final String CREATE_BOOK = "create table Book(id integer primary key autoincrement," +
            "name text,author text,price real,pages integer)";
    //创建管理书籍的类别的表
    public static final String CREATE_CATEGORY = "create table Category(id integer primary autocincrement,category_name text,category_code integer)";
    private Context context;


    /**
     *
     * //@param context上下文
     * @param name  数据库的名称
     * @param factory   返回的游标
     * @param version  数据库的版本
     */
    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.context = context;
    }


    @Override
    public void onCreate(SQLiteDatabase db) {//创建数据库的方法
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);
        Toast.makeText(context, "创建数据库成功!", Toast.LENGTH_LONG).show();
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//更新数据库
        Toast.makeText(context, "更新了数据库", Toast.LENGTH_LONG).show();
        db.execSQL("drop  table if exists Book");
        db.execSQL("drop  table if exists Category");


    }

}





布局代码MainActivity.java

package com.example.databaseoperate;


import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    MyDatabaseHelper myDatabaseHelper;
    private Button create_database;
    private Button insertdata;
    private Button deletedata;
    private Button updatedata;
    private Button query;
    SQLiteDatabase writableDatabase;
    private TextView showContent;
    private String TAG = "MainActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        myDatabaseHelper = new MyDatabaseHelper(MainActivity.this, "BookStore.db", null, 3);
        writableDatabase = myDatabaseHelper.getWritableDatabase();//获取数据库实例
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }


    private void initView() {
        create_database = (Button) findViewById(R.id.create_database);


        create_database.setOnClickListener(this);
        insertdata = (Button) findViewById(R.id.insertdata);
        insertdata.setOnClickListener(this);
        deletedata = (Button) findViewById(R.id.deletedata);
        deletedata.setOnClickListener(this);
        updatedata = (Button) findViewById(R.id.updatedata);
        updatedata.setOnClickListener(this);
        query = (Button) findViewById(R.id.query);
        query.setOnClickListener(this);
        showContent = (TextView) findViewById(R.id.showContent);
        showContent.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.create_database:
// MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)


//                SQLiteDatabase readableDatabase = myDatabaseHelper.getReadableDatabase();
                break;
            case R.id.insertdata://添加数据
                //name text,author text,price real,pages integer
               /* String insertSQL = "insert into Book(name,author,price,pages) values('Android第一行代码','郭霖',76.0,120)";
                String insertSQL2  = "insert into Book(name,author,price,pages) values('Android第一行代码++','郭霖',76.0,120)";
                writableDatabase.execSQL(insertSQL);
                writableDatabase.execSQL(insertSQL2);*/
               String[] bookNmae = new String[]{"三国演义","水浒传","西游记","红楼梦"};
               String[] authors = new String[]{"罗贯中","施耐庵","吴承恩","曹雪芹"};
                double[] prices = new double[]{21, 22, 23, 24};
                int[] pages = new int[]{100, 120, 130, 140};
                ContentValues insert =  new ContentValues();
                for(int i = 0;i<bookNmae.length;i++) {
//                    ContentValues insert =  new ContentValues();
                    insert.put("name",bookNmae[i]);
                    insert.put("author", authors[i]);
                    insert.put("price", prices[i]);
                    insert.put("pages",pages[i]);
                    //insert(String table, String nullColumnHack, ContentValues values)
                    writableDatabase.insert("Book", null, insert);
                    insert.clear();
                }
               /* ContentValues insert =  new ContentValues();
                insert.put("name","西游记");
                insert.put("author", "吴承恩");
                insert.put("price", 99);
                insert.put("pages",300);
                //insert(String table, String nullColumnHack, ContentValues values)
                writableDatabase.insert("Book", null, insert);*/
                break;
            case R.id.deletedata:
                //delete(String table, String whereClause, String[] whereArgs)
                writableDatabase.delete("Book","name = ?",new String[]{"Android第一行代码"});
                break;
            case R.id.updatedata:
                ContentValues contentValues = new ContentValues();
                contentValues.put("price", 99);
                // update(String table, ContentValues values, String whereClause, String[] whereArgs)
                writableDatabase.update("Book",contentValues,"name=?",new String[]{"三国演义"});


                break;
            case R.id.query:
               /* String select = "select * from Book";
                writableDatabase.execSQL(select);
                writableDatabase.q*/
                // Cursor query(String table, String[] columns, String selection,String[] selectionArgs, String groupBy, String having,String orderBy)
                //name text,author text,price real,pages integer
                //查询数据,Cursor表示的是查询的结果集
                Cursor cursor = writableDatabase.query("Book", new String[]{"name", "price"}, null, null, null, null, null);
                if (cursor.moveToFirst()) {
                    do {
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        double price = cursor.getDouble(cursor.getColumnIndex("price"));
                        Log.i(TAG, "name =" + name);
                        Log.i(TAG, "price =" + price);
                    } while (cursor.moveToNext());
                }


                break;
        }
    }
}


猜你喜欢

转载自blog.csdn.net/qq_39745566/article/details/80325655