好的,我的代码中有两种方法:一种用于创建数据库,另一种用于插入记录。他们来了:
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;
}
创建表查询似乎成功并且确认消息显示在控制台上,但插入查询被视为无效。我添加了一个 cout << 查询调用以确保它是正确的并且它是百分百有效的。这有什么问题?
选择方法
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;
}
}