1.
MainActivity.java
package com.example.dbproject;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
DbContect helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new DbContect( MainActivity.this);
Button btn=findViewById(R.id.create);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View V) {
SQLiteDatabase db=helper.getWritableDatabase();
}
});
}
}
2.DbContect.java
package com.example.dbproject;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
public class DbContect extends SQLiteOpenHelper {
private static final int VERSION=1;
private static final String DBNAME="Users.db"; // 创建数据库名叫 Users
private Context mContext;
public DbContect(Context context){
super(context,DBNAME,null,VERSION);
mContext = context;
}
//创建数据库
public void onCreate(SQLiteDatabase db){
//创建密码表 pwd_tb
db.execSQL("create table pwd_tb (pwd varchar(20) primary key)");
//创建收入表 user_tb
db.execSQL("create table user_tb(_id integer primary key autoincrement, money decimal," +
" time varchar(10),type varchar(10),handler varchar(100),mark varchar(200))");
}
//数据库版本更新
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
{
db.execSQL("drop table if exists pwd_tb");
db.execSQL("drop table if exists user_tb");
onCreate(db);
}
}
3.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/create"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00BCD4"
android:textSize="22dp"
android:text="点击创建Users数据库"
>
</Button>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
标签:layout,db,public,Studio,import,Android,tb,android,SQLlite From: https://www.cnblogs.com/zbw-m/p/17161946.html