使用C++打印数据库中的所有列
我正在尝试使用以下代码获取数据库中表的所有数据:使用C++打印数据库中的所有列,c++,mysql,database,C++,Mysql,Database,我正在尝试使用以下代码获取数据库中表的所有数据: const string server = "localhost"; const string username = "root"; const string password = ""; int main() { sql::Driver *driver; sql::Connection *dbConn; sql::Statement *stmt; sql::ResultS
const string server = "localhost";
const string username = "root";
const string password = "";
int main()
{
sql::Driver *driver;
sql::Connection *dbConn;
sql::Statement *stmt;
sql::ResultSet *res;
//get a driver to use to connect to the DBMS
try
{
driver = get_driver_instance();
}
catch (sql::SQLException e)
{
cout << "Could not get a database driver. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
//connect to the DBMS server
try
{
dbConn = driver->connect(server, username, password);
}
catch (sql::SQLException e)
{
cout << "Could not connect to database. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
stmt = dbConn->createStatement(); // Specify which connection the SQL statement should be executed on
// Try to query the database
try
{
stmt->execute("USE test"); // Select which database to use. Notice that we use "execute" to perform a command.
res = stmt->executeQuery("SELECT * FROM users");
}
catch (sql::SQLException e)
{
cout << "SQL error. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
while (res->next())
{
cout << res->getString(1) << endl; //this prints the 1st column
cout << res->getString(2) << endl; //This the 2nd column
cout << res->getString(3) << endl;//This the 3rd column
}
// Clean up
delete res;
delete stmt;
delete dbConn;
//system("pause");
return 0;
}
这将从数据库中进行选择,但一次只打印一列。有没有什么方法可以让我在列上循环,而不仅仅是在行上循环。因此,这里不是使用cout getString2而是使用SQLite获取所有表数据并使用c++迭代结果集的另一个示例:
sqlite3_stmt *selectStmt;
string query = "select * from aTable";
if ( sqlite3_prepare(db, query.c_str(), -1, &selectStmt, 0 ) == SQLITE_OK )
{
int ctotal = sqlite3_column_count(selectStmt); // Count the Number of Columns in the Table
int res = 0;
while ( 1 )
{
res = sqlite3_step(selectStmt); // Execute SQL Statement.
if ( res == SQLITE_ROW )
{
for ( int i = 0; i < ctotal; i++ ) // Loop times the number of columns in the table
{
string s = (char*)sqlite3_column_text(selectStmt, i); // Read each Column in the row.
// print or format the output as you want
*table_out_File << s << " " ;
}
*table_out_File << endl;
}
if ( res == SQLITE_DONE || res==SQLITE_ERROR)
{
*table_out_File << "done " << endl;
break;
}
}
}
什么是ctotal?您的tbleI中的列数更新了我的答案是如何获得的