QT连接数据库,在pro文件中加上QT += sql
连接数据库
QSqlDatabase OpenDB() { QSqlDatabase db=QSqlDatabase::addDatabase("QODBC"); // 注意,对于express版本数据库, 一定要加\\sqlexpress这种后缀 // QString dsn="DRIVER={SQL SERVER};SERVER=192.168.24.71\\sqlexpress;DATABASE=wdgl"; QString url="DRIVER={SQL SERVER};SERVER=192.168.24.71;DATABASE=wdgl"; db.setDatabaseName(url); db.setUserName("sa"); db.setPassword("sa"); if(!db.open()) { qDebug("Error:%s",qPrintable(db.lastError().text())); return db; } qDebug()<<"Database connected sucessfully!"; qDebug() << "ODBC driver valid?" << db.isValid();//连接成功输出true QSqlQuery query; return db; }
增删改操作
QSqlQuery query; qDebug()<<query.exec("insert into wdgl_user (note,password,username)values(‘user...‘,‘123456‘,‘admin‘)");//执行成功输出true
qDebug()<<query.exec("delete from wdgl_user where user_id = 1");//执行成功显示true
qDebug()<<query.exec("update wdgl_user set username = ‘umgsai‘ where user_id = 2");//执行成功显示true
查询操作
void MainWindow::on_pushButton_clicked() { QSqlQueryModel *model = new QSqlQueryModel; model->setQuery("select * from wdgl_user"); model->setHeaderData(0, Qt::Horizontal, tr("用户id")); model->setHeaderData(1, Qt::Horizontal, tr("用户说明")); model->setHeaderData(2, Qt::Horizontal, tr("密码")); model->setHeaderData(3, Qt::Horizontal, tr("用户名")); QTableView *view = new QTableView;//弹出对话框 view->setGeometry(200,200,450,800); view->setWindowTitle("用户列表"); view->setMinimumSize(450,800);//设置不可改变大小 view->setMaximumSize(450,800); view->setModel(model); view->show(); }
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1411180
原文地址:http://shamrock.blog.51cto.com/2079212/1411180