1、头文件
#include <QtCore/QCoreApplication>
#include <QtSql>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include <QString>
#include <QVariant>
#include <QSqlRecord>
2、主函数
int main(int argc,char * argv[])
{
QCoreApplication a(argc,argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");//加载驱动
db.setHostName("localhost");//主机名
db.setDatabaseName("test");//数据库名称
db.setUserName("root");//用户名
db.setPassword("qazqaz");//密码
if(db.open())
{
qDebug()<<"database is established!";//成功加载
}
else
{
qDebug()<<"build error!";
return a.exec();
}
QSqlQuery query;//执行query
query.exec(QObject::tr("create table student(sno varchar(10) not null primary key,sname varchar(20) not null,sclass(10) not null )"));
query.exec(QObject::tr("insert into student (sno, snmae, sclass) values('201200824125','leinei','121')"));
query.exec(QObject::tr("insert into student (sno, sname, sclass) values('201200824126','wuming','131')"));
query.exec(QObject::tr("insert into student (sno, snmae, sclass) values('201200824127','zhouqu','152')"));
query.exec("select from student");
qDebug()<<"sno sname sclass";
while(query.next())
{
qDebug()<<query.value(0).toString()<<" "<<query.value(1).toString()<<" "<<query.value(2).toString();
}
query.clear();
db.close();
return a.exec();
}