<?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) { } } }