好的,我的代码中有2个方法:一个用于创建数据库,另一个用于插入记录。他们在这里:
void DatabaseManager::insert_entry_into_database() {
ostringstream ss;
int choice;
do {
cout << "Press 1 to add a teacher or 2 for student";
cin >> choice;
} while (choice != 1 && choice != 2);
if (choice == 1) {
Teacher t;
ss << "INSERT INTO Teachers ('" << t.get_firstName() << "', '" << t.get_lastName() << "', " << t.get_NID()
<< ", " << t.get_avg_horarium() << ");";
}
const string tmp = ss.str();
const char *query = tmp.c_str();
cout << query;
sqlite3_open("Database.sqlite", &database);
if (sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK) {
cout << "A new record has been added to the database!" << endl;
}
else {
cout << "Error adding new record!";
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
void DatabaseManager::create_database() {
sqlite3_open("Database.sqlite", &database);
char * query = "CREATE TABLE Students (firstName STRING, lastName STRING, NID BIGINT, grade DOUBLE);";
if (sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK) {
cout << "Empty database with students created!" << endl;
}
query = "CREATE TABLE Teachers (firstName STRING, lastName STRING, NID BIGINT, avg_horarium INT);";
if (sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK) {
cout << "Empty database with teachers created!" << endl;
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
我在主函数中测试它们:
int _tmain(int argc, _TCHAR* argv[])
{
DatabaseManager m;
m.create_database();
m.insert_entry_into_database();
return 0;
}
create table查询似乎是成功的,并且控制台上显示确认消息,但insert查询被视为无效。我添加了一个cout&lt;&lt;查询调用以确保它是正确的并且百分之百有效。这有什么问题?
选择方法
vector<vector<string>> DatabaseManager::select_entry() {
vector<vector<string>> results;
sqlite3_open("Database.sqlite", &database);
char* query = "SELECT firstName FROM Teachers WHERE firstName = 'Ivan';";
cout << query;
if (sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK) {
int cols = sqlite3_column_count(statement);
int result = 0;
while (true) {
result = sqlite3_step(statement);
if (result == SQLITE_ROW) {
cout << "test";
vector<string> values;
for (int i=0; i<cols; i++) {
cout << (char*)sqlite3_column_text(statement, i);
values.push_back((char*)sqlite3_column_text(statement, i));
}
results.push_back(values);
}
else break;
}
sqlite3_finalize(statement);
string error = sqlite3_errmsg(database);
if(error != "not an error") cout << query << " " << error << endl;
return results;
}
}
答案 0 :(得分:1)
valid syntax for an INSERT statement是
INSERT INTO MyTable(Col1, Col2, ...) VALUES (value1, value2, ...)
或
INSERT INTO MyTable VALUES (value1, value2, ...)
您已省略VALUES
,因此SQLite认为括号内的内容是列名列表。
数据库文件由sqlite3_open
自动创建。
您需要致电sqlite3_step
来实际执行命令。