创建一个数据库类:
package com.example.hellonote;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class NotesDB extends SQLiteOpenHelper{
public static final String TABLE_NAME="notes";
public static final String CONTENT="content";
public static final String ID="_id";
public static final String TIME="time";
public NotesDB(Context context) {
super(context, "notes", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
//拼这个代码容易出错
db.execSQL("create table "+TABLE_NAME+"("+ID
+" integer primary key autoincrement,"+CONTENT
+" text not null,"+TIME+" text not null)");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
测试创建的sqlite:
package com.example.hellonote;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
public class MainActivity extends Activity {
private NotesDB notesDB;
private SQLiteDatabase dbWriter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notesDB=new NotesDB(this);
dbWriter=notesDB.getWritableDatabase();
addDB();
}
//添加数据
public void addDB(){
ContentValues cv=new ContentValues();
cv.put(NotesDB.CONTENT, "Hello");
cv.put(NotesDB.TIME, getTime());
dbWriter.insert(NotesDB.TABLE_NAME, null, cv);
}
public String getTime(){
SimpleDateFormat format=
new SimpleDateFormat("yyyy年mm月dd日 hh:mm:ss");
Date curDate=new Date();
String str=format.format(curDate);
return str;
}
}