Qt operates Access database

http://blog.csdn.net/xysq/article/details/3950722

Qt provides QtSql module for database access to realize the seamless integration of database and Qt application program. The QtSql module uses driver plugins to communicate with different database interfaces. Qt has its own QODBC driver, and accesses ODBC-supporting databases through the ODBC driver provided on the windows platform, such as Ms Access, SQL Server, etc. (Windows XP comes with ODBC Driver for Access and SQL Server). Below we use QODBC to access the Access database.

    Before using the QtSql module, you need to enter QT += sql in the working file (.pro), and include #include <QtSql> in the header file.

       QSqlDatabase provides a connection interface for accessing a database. To establish a connection, you need to call the member function of QSqlDatabase: addDatabase.

       QSqlDatabase addDatabase(const QString & type, const QString & connectionName = QLatin1String( defaultConnection ) ) , the parameter type is the driver name, we use "QODBC" here, the second parameter is the connection name, the default value is the default connection, here we put The connection name is set to "test". Here if you use the connection name of the same connection, the new connection will replace the old connection.

     After creating the connection, you can use the static function database of QSqlDatabase to get the connection later.

  QSqlDatabase database ( const QString & connectionName = QLatin1String( defaultConnection ), bool open = true ) , the parameter defaultConnection is the database connection name, here we set "test" above, and the parameter open is whether to open the database connection.

   setDatabaseName ( const QString & name ) function, parameter name, for QODBC driver, here isthe DSN file name or a connection string, here we use the connection string:"DRIVER={Microsoft Access Driver (*.mdb)};FIL= {MS Access};DBQ=test.mdb", test.mdb is the name of the Access data file.

Well, use the code to access the test.mdb database.

 

//Create a database connection
void MainWindow::connectDB()
{
//Get whether there is a database connection
    QSqlDatabase dbconn = QSqlDatabase::database("test", false);
 
    if(dbconn.isValid())//Exit if there is a connection
    {
        return;
    }
   // Create a database connection named "test"
dbconn = QSqlDatabase::addDatabase("QODBC", "test");
    QString dsn = QString("DRIVER={Microsoft Access Driver (*.mdb) };FIL={MS Access};DBQ=test.mdb");
    dbconn.setDatabaseName(dsn);
}
//Query database data
void MainWindow::queryDB()
{ //Get the connection     QSqlDatabase
    of the connection name database "test"
dbconn = QSqlDatabase::  database("test", false); 
    dbconn.open();
    QSqlQueryModel q;
    q.setQuery(tr("SELECT * FROM companyinfo"),dbconn);
}

Guess you like

Origin blog.csdn.net/Zhangchen9091/article/details/39609215