ios - 这个Sqlite3语句可以吗?

标签 ios objective-c sql sqlite

我是 sqlite 的菜鸟,不太确定如何操作。

我想要一个有一堆行的数据库,每行包含一个单词。当用户键入一个词时,我将通过检查它是否在数据库中来验证它。

我想我没有的东西,也不知道如何创建,是索引吗?我该如何插入?如何编写查询以利用索引?

我还有两列,“id 和 word”。有 id 好还是只是占用空间?

这是我到目前为止得到的:

CREATE TABLE words (id INTEGER PRIMARY KEY, word VARCHAR(15));

我不希望单词超过 15 个字符,所以我设置了 VARCHAR(15);

INSERT INTO words(word) VALUES('hello');
INSERT INTO words(word) VALUES('bye');
etc. for all words

检查一个词:

NSString *sql = [NSString stringWithFormat:@"SELECT EXISTS(SELECT 1 FROM words WHERE word=\"%@\" LIMIT 1)", word];
const char *sqlStatement = [sql UTF8String];

if (sqlite3_prepare_v2(db, sqlStatement, -1, &selectStmt, NULL) == SQLITE_OK)
{
    int count = 0; 
    while(sqlite3_step(selectStmt) == SQLITE_ROW)
    {
        count = sqlite3_column_int(selectStmt, 0);
    }

    NSLog(@"COUNT: %i",count);

    //If count is 1, we have a match.  
}

最佳答案

是的。你的陈述没问题。

您还可以使用 ' 代替 ":

NSString *sql = [NSString stringWithFormat:@"SELECT EXISTS(SELECT 1 FROM words WHERE word='%@' LIMIT 1)", word];

Is it good to have the id or does it just take up space?

这取决于你的需要,我建议你应该保留一个Id字段作为主键。


要创建索引,您可以使用:

CREATE INDEX yourIndexName ON yourTableName ( yourColumnName )

有关索引检查的更多信息 sqlite

关于ios - 这个Sqlite3语句可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14353742/

相关文章:

ios - 在 uitapGestureRecognizer 上进行分类?

ios - 使用指针设置属性而不是发送对象消息

ios - 在 dispatch_async 中上传 UIImage

ios - Swift UICollectionView 在点击时更新单元格标签而不是实时更新

ios - iOS 中的多列文本

sql - Rails 查找等于两个日期之间的日期

java - Selenium SQL 数据库连接

ios - 无法识别 UITableViewCell 中的 UITapGestureRecognizer

ios - Revmob 使我的应用程序崩溃

mysql - SELECT 当前行和上一行 WHERE 条件