sqlite创建数据库并创建一个表

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.cunli.sqllite001.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="新建数据库并创建一个表"
        android:gravity="center"
        android:onClick="openDb"/>
</RelativeLayout>
package com.example.cunli.sqllite001;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
SQLiteDatabase sqLiteDatabase;
    private Context context = MainActivity.this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void openDb(View view){
//以可读写的方式打开或创建一个数据库
    //使用MyOpenHelper打开数据库
        MyOpenHelper myOpenHelper = new MyOpenHelper(context,"school",null,1);
        //使用getReadableDatabase()得到SQLiteDatabase一个对象
        sqLiteDatabase = myOpenHelper.getReadableDatabase();

        //插入一条数据
        String sql = "insert into Students (student_name,mobile,gender) values (?,?,?)";
        sqLiteDatabase.execSQL(sql,new Object[]{"zhangsan","12345678900",Boolean.valueOf(false)});
        //关闭数据库
        sqLiteDatabase.close();
    }
    class MyOpenHelper extends SQLiteOpenHelper{
        public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
//只会在第一次创建数据库的时候调用
        @Override
        public void onCreate(SQLiteDatabase db) {
            String createSQL = "CREATE TABLE IF NOT EXISTS Students (_id INTEGER NOT NULL,student_name CHAR(20) NOT NULL,mobile CHAR(20),gender BOOLEAN,PRIMARY KEY(_id))";
            db.execSQL(createSQL);

        }
//这里不需要升级,保留空方法即可
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }
    }
}

 

    原文作者:sqlite
    原文地址: https://www.cnblogs.com/thankyouGod/p/6288815.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞