前言
测试批量插入到SQLite的时长,共9599条数据
方法1:单条进行插入,耗时约2分钟
方法2:使用事务进行插入,耗时约2秒
关于事务的使用步骤如下所述。
一、通过Visual Studio 生成API
1、 使用(Visual Studio )vs创建一个“ASP.NET Web应用程序”
项目名称设为”WebApplicationT2“,点击创建,然后选择Web API进行创建
2、在项目中引入SQL server数据表
在项目中新建项,选择“数据”,部分步骤如下所示:
数据表结构如下所示,其中idx为主键,自增。
3、 在项目的Controller中添加控制器“StudentController”
创建一个方法,得到表(StudentInfo)中所有数据,代码如下:
4、为使返回数据的格式为json,在“Global.asax”中进行初始设定
添加代码:GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
5、 将此项目进行发布,得到其WebAPI
(1)在VS上发布
(2)打开IIS管理器,创建服务
打开“控制面板”,选择“系统和安全”,打开“管理工具”,选择“Internet Information Services (IIS)管理器”。
结果如下,其中API:http://ip地址/WebApplicationT2/Api/Student
二、 在Android Studio中调用webApi
1、 创建Empty Activity项目
2、在build.gradle中导入包
添加:
implementation 'com.mcxiaoke.volley:library:1.0.19' implementation 'com.google.code.gson:gson:2.8.0'
3、 关于数据库
(1) 在utils包中创建DBContext.class
package si.ftc.studentapplication.utils;
import android.content.Context;
import android.content.ContextWrapper;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Environment;
import android.provider.SyncStateContract;
import android.util.Log;
import java.io.File;
//数据库
public class DBContext extends ContextWrapper {
public DBContext(Context base){super(base);}
@Override
public File getDatabasePath(String name){
return new File(getFilePath(),name);
}
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler){
SQLiteDatabase result=SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name),null);
return result;
}
//得到文件路径
public final String getFilePath(){
String sd_path="";//预设放在sd目录中
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdFile=Environment.getExternalStorageDirectory();
sd_path=sdFile.getPath()+"/"+"StudentApplication";
Log.d("folder",sd_path);
File dirFile=new File(sd_path);
if(!dirFile.exists()){
dirFile.mkdirs();
}
}else {
Log.d("No storage","no storage");
}
return sd_path;
}
}
(2) 在db包中,创建StudentDBHelper类(创建数据表)
package si.ftc.studentapplication.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.sql.SQLDataException;
public class StudentDBHelper extends SQLiteOpenHelper {
public final static String _TableName="StudentInfo";
public final static String _Idx="idx";
public final static String _Name="name";
public final static String _Age="age";
private final static int _DBVersion = 1;
public static final String _DBName = "StudentDB.db";
public StudentDBHelper(Context context){
super(context,_DBName,null,_DBVersion);
}
@Override
public void onCreate(SQLiteDatabase db){
final String creatable1="CREATE TABLE IF NOT EXISTS "+_TableName
+"("+_Idx+" int,"
+_Name+" VARCHAR(50),"
+_Age+" int)";
db.execSQL(creatable1);
}
@Override
public void onUpgrade(SQLiteDatabase db,int a,int b){
db.execSQL("DROP TABLE IF EXISTS "+_TableName);
onCreate(db);
}
}
(3)在model包中添加StudentModel类(实体类)
package si.ftc.studentapplication.model;
public class StudentModel {
public int idx;
public String name;
public int age;
public int getIdx() {
return idx;
}
public void setIdx(int idx) {
this.idx = idx;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4、 在activity_main.xml中添加一个按钮,用于测试“批量插入”功能
5、MainActivity 使用事务进行处理
package si.ftc.studentapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import si.ftc.studentapplication.db.StudentDBHelper;
import si.ftc.studentapplication.model.StudentModel;
public class MainActivity extends AppCompatActivity {
private RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestQueue = Volley.newRequestQueue(MainActivity.this);
View view=this.getWindow().getDecorView();
Button insertButton=(Button) view.findViewById(R.id.button_Insert);
insertButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
deleteAll();//删除之前的记录
String getStudentAllDataurl = "http://IP地址/WebApplicationT2/Api/Student";//vs发布的webapi 地址,如:http://10.113.126.218/WebApplicationT2/Api/Student
getStudentAllData(getStudentAllDataurl);
}
});
}
/**
* 删除所有的数据
*/
public void deleteAll(){
SQLiteDatabase db=new StudentDBHelper(MainActivity.this).getWritableDatabase();
db.delete("StudentInfo",null,null);
db.close();
}
/**
* 通过API得到json数据
* */
public void getStudentAllData(String dataURL){
JsonArrayRequest allJson = new JsonArrayRequest(dataURL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
parseJson(response.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("error_getStudentAllData",error.toString());
}
});
requestQueue.add(allJson);//将创建的请求放入请求队列中
}
/**
* 将json数据转换为StudentModel数组
*/
public void parseJson(String waitString) throws JSONException{
Gson gson=new Gson();
StudentModel[] studentModelList= gson.fromJson(waitString, StudentModel[].class);
InsertStudentInfo(studentModelList);
}
/**
* 插入数据--事务
*/
public void InsertStudentInfo(StudentModel[] studentModelList){
SQLiteDatabase db =new StudentDBHelper(MainActivity.this).getWritableDatabase();//SQLiteDatabase: /data/user/0/si.ftc.studentapplication/databases/StudentDB.db
try{
String insertSQL="insert into StudentInfo(idx,name,age) values(?,?,?)";
SQLiteStatement sqLiteStatement=db.compileStatement(insertSQL);
db.beginTransaction();
for(StudentModel studentModel:studentModelList){
try{
sqLiteStatement.bindLong(1,studentModel.idx);
sqLiteStatement.bindString(2,studentModel.name);
sqLiteStatement.bindLong(3,studentModel.age);
sqLiteStatement.executeInsert();
}catch (Exception ex){
continue;
}
}
db.setTransactionSuccessful();
Log.e("成功","数据成功插入数据库");
Toast.makeText(this, "数据成功插入数据库", Toast.LENGTH_SHORT).show();
}catch (Exception exception){
exception.printStackTrace();
}finally {
db.endTransaction();
db.close();
}
}
}