MySql数据库服务器已打开
#include <QtCore/QCoreApplication>
#include <QtSql>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QString>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//从MySql驱动程序中获取一个MySql数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");//指字数据服务器名称
db.setDatabaseName("test");//连接一个已存在的数据库
db.setUserName("root");//设置登录名
db.setPassword("");//设置登录密码 我的数据库密码为空,不知道怎么添加数据库的密码
//打开数据库
if(db.open())
{
qDebug()<<"database is establelished!";
}
else
{
qDebug()<<"build error!";
return a.exec();
}
QSqlQuery query;//定义一个QSqlQuery类弄的变量
//创建数据库表,并填充数据 student表在终端上已创建好
//query.exec(QObject::tr("create table student(snovar char(10) not null primary key,sname varchar(20) not null,sclass varchar(10) not null)"));
query.exec(QObject::tr("insert into student(sno,sname,sclass) value('2009002','lusy','0902')"));
//执行数据库查询语句
query.exec(QObject::tr("select * from student"));
QSqlRecord rec=query.record();//返回查询语句执行的结果
int count = rec.count();//获取查询到的记录的列数
qDebug()<<"Number of coloumn:"<<count;
//获取查询到的记录,并输出到控制台
while(query.next())
{
rec=query.record();
int snocol = rec.indexOf("sno");//返回该列的索引
int snamecol=rec.indexOf("sname");
int sclasscol=rec.indexOf("sclass");
QString value1 = query.value(snocol).toString();//获取该殊数据值
QString value2 = query.value(snamecol).toString();
QString value3 = query.value(sclasscol).toString();
qDebug()<<"sno:"<<value1<<"\t"<<"sname:"<<value2<<"\t"<<"sclass:"<<value3;
}
query.clear();//清空查询语句,并释放内存空间
db.close();//关闭数据库连接
return a.exec();
}
/*
example4_1.pro文件中添加
QT += core\
sql
编译运行时出错
[root@localhost example4_1]# ./example4_1
QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QPSQL7 QPSQL
build error!
先查下libqsqlmysql.so库的位置
[root@localhost example4_1]# locate libqsqlmysql.so
/usr/lib/qt4/plugins/sqldrivers/libqsqlmysql.so
把libqsqlmysql.so库复制到QT安装的驱动目录下
[root@localhost sqldrivers]# cp /usr/lib/qt4/plugins/sqldrivers/libqsqlmysql.so /opt/qtsdk-2010.04/qt/plugins/sqldrivers/
运行结果
[root@localhost example4_1]# ./example4_1
database is establelished!
Number of coloumn: 3
sno: "21109237" sname: "yijun" sclass: "201047"
sno: "2009001" sname: "lilei" sclass: "0901"
sno: "2009002" sname: "lusy" sclass: "0902"
*/