您的位置:首页 > 编程语言 > Qt开发

Qt连接Sql Server数据库

2015-06-12 15:58 387 查看
1.在工程文件.pro内加上QT +=
sql
2.创建一个表并插入数据
create table person
(
id int primary key,
name char (15),
age int
)
insert into person values ('01' , '周杰伦', '20' );
insert into person values ('02' , '王杰', '22' );
insert into person values ('11' , '刘涛', '23' );
insert into person values ('12' , '张杰', '25' );
insert into person values ('13' , '成龙', '26' );
insert into person values ('14' , '李毅', '35' );
insert into person values ('15' , '许嵩', '28' );
insert into person values ('16' , '方力申', '21' );


3.代码实现

#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>

static bool createConnection()

{

QSqlDatabase db=QSqlDatabase::addDatabase("QODBC");

db.setDatabaseName(QString("DRIVER={SQL SERVER};"
"SERVER=%1;"
"DATABASE=%2;"
"UID=%3;"
"PWD=%4;"
).arg("GDCZT").arg("BookManageSystem")

.arg("sa").arg("ggjk"));

if(!db.open())

{

qDebug()<<"the database can't be connected";

return false;

}

qDebug()<<"the database is already connected";

return true;

}

int main(int argc, char *argv[])

{

QCoreApplication a(argc, argv);

if(!createConnection())

{

qDebug()<<"can't connect";

return 1;

}

QSqlQuery query;

query.exec("select * from person where age>21");

while(query.next())

{

int id=query.value(0).toInt();

QString name=query.value(1).toString();

int age=query.value(2).toInt();

qDebug()<<"the id is:"<<id<<"\t"<<"name is:"<<name<<"the age is:"<<age;

}

return a.exec();

}


4.运行结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: