android(Sqlite数据库)-14

    体验了一个项目发现数据库这玩意真Tnnd的有用,所以哥哥我又立马回来看数据库了nnd的以前看过的,还看了两次,忘记了。。。

    还有点记忆SQLiteOpenHelper是android专门提供的数据库管理类

    有两个抽象方法:

    onCreate()

    onUpgrade();

    有两个非常重要的实例方法:

    getReadableDatabase()和getWritableDatabase()这两个方法用来创建、打开数据库,与C语言打开文件中的r打开与W打开是一个道理。

    SQLiteOpenHelper中有两个构造方法可供重写,一般用参数少一点的那个方法构造即可。这个构造方法中接收四个参数,区别为 Context  数据库名 Cursor(一般传入null)最后一个为null, 数据库文件一般存放在/data/data/<package name>/databases/目录下

    比如我点下按键创一个数据库,并让创一个表:

    先写个数据库管理类:用来创数据库与相关的表

public class MyBookStoreHelper extends SQLiteOpenHelper {
    /**
    *创建表
    */
    public static final String CREATE_BOOK = "create table Book("
            + "id       integer primary key autoincrement,"
            + "author   text,"
            + "preaci   real,"
            + "pages    integer,"
            + "name     text)";
    private Context mContext;
    public MyBookStoreHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
        super(context, name, factory, version);
        mContext = context;
    };

    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);
  Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL("drop table if exists Book");
        db.execSQL("drop table if exists Category");
        Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
onCreate(db);
}}
调用这个类就可以创建数据库了:

public class MainActivity extends AppCompatActivity {

    private MyBookStoreHelper dbHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dbHelper = new MyBookStoreHelper(this, "BookStore.db", null, 1);
        Button createDatabase = (Button) findViewById(R.id.create_database);
        createDatabase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dbHelper.getWritableDatabase();
            }
        });
    }
}

我们在做项目的时候会再建一个类用来做数据库的操作当然在构造这个类时创数据库不会是点按键的时候创了;

数据升级就是删除表再重表,但是要注意数据库的版本号要比第一次的高才会触发;


创建和升级都可以了的话接下来就是插入、查询、删除、修改之类的东西了。

SQLiteDatabase类中提供insert()方法用来添加数据。

Button insertData = (Button) findViewById(R.id.insert_data);
insertData.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", "The Da Vinci Code");
        values.put("author", "Dan Brown");
        values.put("pages", 454);
        values.put("price", 19.96);
        db.insert("Book", null, values);
        values.clear();
    }
});
当然也可以用Sql语句来查询。


更新数据库:

updata()方法:与插入数据一样构建一个ContentValues对象对数据进行操作:

Button updateData = (Button) findViewById(R.id.update_dababase);
updateData.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("price", 10.99);
        db.update("Book", values, "name = ?", new String[]{"The Da Vinci Code"});
    }
});


删除数据:删除数据与更新数据差不多一样:都是根据条件进行操作的。

Button deleteData = (Button)findViewById(R.id.delete_data);
deleteData.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("Book", "page>?", new String[]{"500"});
    }
});


最后就是数据库的大事了查询数据库,这个东西搞起来就有点蛋碎了查的方法多不胜数,我这种小菜肯定先会个简单的还是可以的

SQLiteDatabase 提供的数据库查询的方法。query()

有七个参数,看起来有点蛋碎;

table                         指定表名

columns                  指定列名

selection                 指定条件

selectionArgs         占位符提供具体的值

groupBy                   指定需要group by 列

having                      对group by 后的结果进一步约束

orderBy                    指定查询结果的排序方式

参数挺多的,不过不是所有的参数都要搞一个值去传进去

每个查询都返回一个Cursor.

我来搞行代码玩玩吧。

Button queryButton = (Button) findViewById(R.id.Select_data);
deleteData.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("Book", null, null, null, null, null, null, null);
        if(cursor.moveToFirst()){
            do{
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String author = cursor.getString(cursor.getColumnIndex("author"));
                int pages = cursor.getInt(cursor.getColumnIndex("pages"));
                double price = cursor.getDouble(cursor.getColumnIndex("price"));
            }while(cursor.moveToNext());
        }
        cursor.close();
    }
});
呀,呀,呀,查询主要是对cursot光标对象的操作,遍历每行,从面拿出每一列的信息。

这些就是SQLite一个常用的操作了,最后看下界面的那些按键

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="ouyang.my_db.activity.MainActivity">

    <LinearLayout
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <Button
            android:id="@+id/create_database"
            android:layout_width="88dp"
            android:layout_height="wrap_content"
            android:text="CreateDatabase"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="0dp" />

        <Button
            android:id="@+id/insert_data"
            android:layout_width="88dp"
            android:layout_height="wrap_content"
            android:text="Insert_data"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="0dp" />

        <Button
            android:id="@+id/update_dababase"
            android:layout_width="88dp"
            android:layout_height="wrap_content"
            android:text="Updata_data"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="0dp" />

        <Button
            android:layout_width="88dp"
            android:layout_height="wrap_content"
            android:id="@+id/delete_data"
            android:text="Delete_data"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="0dp" />
        <Button
            android:layout_width="88dp"
            android:layout_height="wrap_content"
            android:id="@+id/Select_data"
            android:text="Delete_data"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="0dp" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

look里面什么好东西都没有是不是。

如果不用SQLiteDatabase类里的方法,还有一种方式,这是大神级别的人使用的方法:

插入:

db.execSQL("insert into Book(name, author, pages, price) values(?,?,?,?)"),

new String[]{"The Da Vinci Code", "Dan Brown", "454", "16.96"});

更新:

db.execSQL("update Book set price = ?" where name = ?", new String[]{"10.99", The Da Vinci Code"});

删除:

db.execSQL("delete from Book where pages > ?", new String[]{"500"});

查询:

db.rawQuery("select * from Book", null);

可以看到主要是execSQL(),除了rawQuery()是查询的方法外。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值