在SQLite中单击按钮即可动态创建表 [英] Dynamic table creation on button click in SQLite
问题描述
我正在创建一个登录应用程序,我想为每个用户单击注册按钮时创建一个表.问题是,我正在使用其唯一的电子邮件ID作为表名.后来我知道表名不能有特殊字符,例如"@".请为我建议一种创建带有特殊字符(如"@")的名称的表的方法.否则,请为我提供一种方法,为每个用户单击注册按钮时为其创建具有唯一名称的表.
I am creating a login application and I wanted to create a table for each user when they click the register button. The problem is, I am using their unique email id as table name. Later I learned that table names cannot have special characters like "@". Please suggest me a way to create table with names having special characters like "@". Or else, please suggest me a way to create tables with unique names for each user when they click the register button.
请注意:下面给出的代码中的"TABLE_NAME"是另一个包含注册用户详细信息的表.
Please Note :"TABLE_NAME" in the code given below is another table containing registered user details.
代码如下:
public boolean insertData(String name, String email, String mobile, String pass){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("create table "+email+"(Choice TEXT, Q1 INTEGER, Q2 INTEGER, Q3 INTEGER, Q4 INTEGER, Q5 INTEGER)");
ContentValues cv = new ContentValues();
cv.put(NAME, name);
cv.put(EMAIL, email);
cv.put(MOBILE, mobile);
cv.put(PASSWORD, pass);
long result = db.insert(TABLE_NAME,null,cv);
db.close();
if(result == -1)
return false;
else
return true;
}
推荐答案
在SQL中,标识符可以用双引号引起来.标识符中的任何双引号都必须加倍以转义;并且在Java字符串中,双引号必须以反斜杠转义:
In SQL, identifiers can be quoted with double quotes. Any double quotes inside the identifier must be doubled to escape them; and in Java strings, double quotes must be escaped with a backslash:
String sqlTableName = "\"" + email.replace("\"", "\"\"") + "\"";
db.execSql("CREATE TABLE " + sqlTableName + "...");
但是,将数据放入表名不是一个好主意,因为它不能像其他所有数据一样被查询和修改.
However, putting data into the table name is a bad idea, because it cannot be queried and modified like all your other data.
最好使用一个表,然后将该信息放入另一列:
Better use a single table, and put that information into another column:
CREATE TABLE Users(EMail TEXT, Choice TEXT, Q...);
这篇关于在SQLite中单击按钮即可动态创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!