sqlite作为跨平台的一种小型数据库,进行数据储存查找还是蛮方便的,但是不熟悉SQL语句还是挺烦人的,先记录下来,看看以后用得上不。
数据的更新与保存:
/**
* 保存数据
* */
protected void saveDate(){
SimpleDateFormat sDateFormat = new SimpleDateFormat(
"yyyy年MM月dd日HH时mm分", Locale.getDefault());
String date = sDateFormat.format(new java.util.Date());
//创建文件夹
File file = new File("/sdcard/TreadWear");
boolean isDirectoryCreated=file.exists();
if (!isDirectoryCreated) {
isDirectoryCreated= file.mkdir();
}
if(isDirectoryCreated) {
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase("/sdcard/TreadWear/date.db",null);
//创建一个表
try {
db.execSQL("create table wheel_date(" +
"WheelId varchar(50) NOT NULL primary key," +
"TreadWear varchar(50) NULL," +
"WheelThick varchar(50) NULL," +
"RimWidth varchar(50) NULL," +
"RimThick varchar(50) NULL," +
"Time varchar(50) NOT NULL,"+
"AllDate varchar(50) NOT NULL)");
}catch (Exception e) {
//This happens on every launch that isn't the first one.
Log.w("一般第一次不发生的错误", "Error while creating db: " + e.toString());
}
/**
* 更新插入数据
* */
try {
db.execSQL("REPLACE INTO wheel_date VALUES('"+
getIntent().getStringExtra("wheel_date") +"','"+
temp[0] +"','"+
temp[1] +"','"+
temp[2] +"','"+
temp[3] +"','"+
date +"','1')");
}catch (Exception e) {
//This happens on every launch that isn't the first one.
Log.w("一般不会发生的错误", "Error while REPLACE INTO db: " + e.toString());
}
Toast.makeText(DateActivity.this, "数据已保存", Toast.LENGTH_SHORT).show();
db.close();
finish();
overridePendingTransition(0, R.anim.zoomout);
}else {
Toast.makeText(DateActivity.this, "保存数据失败", Toast.LENGTH_SHORT).show();
}
}
需要权限:
<!--SD卡读写权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<!--在sdcard中创建/删除文件的权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
通过string进行查找数据:
//读取数据
Cursor c = db.rawQuery("SELECT* FROM wheel_date WHERE WheelId = ?", new String[]{string});
int i = 0;
while (c.moveToNext()) {
i++;
}
if(i == 0){
Toast.makeText(SearchDateActivity.this, "无数据", Toast.LENGTH_SHORT).show();
}else {
c.moveToFirst();
date_1.setText(c.getString(c.getColumnIndex("TreadWear")));
date_2.setText(c.getString(c.getColumnIndex("WheelThick")));
date_3.setText(c.getString(c.getColumnIndex("RimWidth")));
date_4.setText(c.getString(c.getColumnIndex("RimThick")));
date_5.setText(c.getString(c.getColumnIndex("Time")));
}
c.close();
删除数据库数据,一条代码就够了:
db.delete("wheel_date","WheelId = ?",new String[]{s_date});
然后需要注意的是记得关闭数据库,要写在返回键跟销毁里面。
主要就是对于SQL语句的不熟悉而记录,作为程序员,SQL语句应该是基础的基础,还是需要加强学习啊!