Qt MySQL数据库访问测试程序

/**********************数据库准备工件**************************/
/*
 MySQL -p -u root
 show databases;
 create database testmysql
 create table login(username varchar(20),idnumber varchar(20));
 insert into login values('huise','123456');
 show table login;
 select * from login;
*/
#include <QtGui>
#include <QtSql>
int main(int argc, char *argv[])
{

QCoreApplication a(argc, argv);
    QString m_name;
    QString m_password;
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("testmysql");
    db.setUserName("root");
    db.setPassword("72074918");
    if(!db.open())
    {
        qDebug()<<"Failed to mysql";
    }

QSqlQuery query;
    if(query.exec("select username,idnumber from login"))
    {
        qDebug()<<"failed query.exce";
    }
    while(query.next())
    {
         m_name = query.value(0).toString();
         m_password = query.value(1).toString();
         qDebug()<<m_name;
         qDebug()<<m_password;
    }
    return 0;
}

注意:编译时不要忘记了在.pro中添加 QT     +=sql

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/pfszy.html