每日总结2023/3/1日
今天学习安卓连接本地数据库sqllite
教学参考视频Android Studio使用自带SQLite数据库/SQLite数据库/SQLiteOpenHelper帮助类_哔哩哔哩_bilibili
代码
<?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="com.example.a86191.sqllite.MainActivity"> <Button android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/creat_database" android:text="创建数据库"/> <Button android:layout_width="100dp" android:layout_height="100dp" android:text="添加" android:id="@+id/add_data"/> </android.support.constraint.ConstraintLayout>
package com.example.a86191.sqllite; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private MyDatabaseHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHelper=new MyDatabaseHelper(this,"StudentStore.db",null,1); Button createDatabase=(Button)findViewById(R.id.creat_database); createDatabase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dbHelper.getWritableDatabase(); } }); } }
package com.example.a86191.sqllite; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; /** * Created by 86191 on 2023/3/1. */ public class MyDatabaseHelper extends SQLiteOpenHelper{ public static final String CREAT_Student="create table Student(" +"id interger ," +"name text," +"number text)"; private Context mContext; public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); mContext=context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREAT_Student); Toast.makeText(mContext,"Creat succeeded",Toast.LENGTH_SHORT); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
本次实现的·是创建学生表,
通过这里我们把保存的数据库转存到其他文件下,再用sqllite可视化工具打开数据库表查看