这里咱们以创建一个Book表为例。
首先创建一个类MyDataHelper并继承SQLiteOpenHelper:
package com.example.sqlapplication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK = "create table book(" +
"_id integer primary key autoincrement," +
"author text," +
"price real," +
"pages integer," +
"name text)";
private Context mContext;
public MyDatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
Toast.makeText(mContext, "Create succeed", Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}接着,我们创建一个按钮,点击之后就能成功建表那种:
<?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:orientation="vertical" android:background="#ffffff" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/create_database" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Create data" android:textColor="#000000" android:textSize="20dp"/> </LinearLayout>
主代码,记得,引进MyDatabaseHelper类,然后传入:1.context,2."数据表名",3,游标:Null.4.version:1
package com.example.sqlapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button create_database;
private MyDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,1);
create_database = (Button)findViewById(R.id.create_database);
create_database.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dbHelper.getReadableDatabase();
}
});
}
}點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦