我的服务中有以下功能:
private void saveToDB(String sender, String message, String time) {
DBHandler db = new DBHandler(getApplicationContext(), sender);
db.insertOrCreateTable(sender, message, time);
}
这是我的数据库处理程序类:
public class DBHandler extends SQLiteOpenHelper {
// All Static variables
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Mo";
private static String mSender;
private static final String KEY_ID = "id";
private static final String KEY_SENDER ="sender";
private static final String KEY_MSG = "msg";
private static final String KEY_TIME ="time";
//constructor
public DBHandler(Context context, String sender) {
//higher db version when user needs to create new table
super(context, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase db = this.getWritableDatabase();
mSender = sender;
}
// Contacts table name
private static final String TABLE_MESSAGES = mSender;
private String CREATE_MESSAGES_TABLE = "Create Table " + TABLE_MESSAGES +
"("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_SENDER + " TEXT, "
+ KEY_MSG + " TEXT, "
+ KEY_TIME + " TEXT" + ")";
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_MESSAGES_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
onCreate(db);
}
public void insertOrCreateTable(String s,String m,String t) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_SENDER, s); // Message Sender
values.put(KEY_MSG, m); // Message Message
values.put(KEY_TIME, t); // Message Time
// Inserting Row
db.insert(mSender, null, values);
db.close();
}
}
现在,我尝试动态创建表,但它总是返回错误:
E/SQLiteLog: (1) near "65": syntax error
03-09 12:03:13.813 20828-21609/com.example.asus.service E/SQLiteDatabase: Error inserting sender=65 time=12:03 msg=C
android.database.sqlite.SQLiteException: near "65": syntax error (
code 1): , while compiling: INSERT INTO 65(sender,time,msg) VALUES (?,?,?)
任何想法或建议?我也以不同的方式将它发布在一个帖子中,所以请随意查看它(可能有助于你更好地理解我的问题) 这是链接:How do I dynamically add tables in android sqlite?
我做错了什么?
答案 0 :(得分:0)
如果您的表名为65
,则应使用' '
进行插入。
而不是:
INSERT INTO 65(sender,time,msg) VALUES (?,?,?)
尝试:
INSERT INTO '65'(sender,time,msg) VALUES (?,?,?)