(引)推荐QT学习资料(Qt教程汇总)
(原)Qt学习笔记之容器类

(摘)Qt之数据库编程

孔令春 posted @ 2009年10月29日 22:33 in 开发语言 with tags QtSql模块 , 14625 阅读

摘自:《C++ Gui Qt4编程》

        在Qt中,实现与数据库编程相关的模块是QtSql模块,该模块提供了一组与平台以及数据库种类无关的SQL数据库访问接口。此接口通过驱动程序与各种数据库进行通信。Qt桌面版提供的驱动程序如下:

驱动程序 数据库
QDB2

IBM DB2 7.1版以及更高版本

QOCI 甲骨文Oracle
QODBC ODBC(包括微软公司的SQL服务器)
QMYSQL MySQL
QPSQL PostgreSQL的7.3版以及更高级的版本

 

一、连接数据库

bool connDB()
{
    QSqlDatabase db = QSqlDatabase::addDatabase(dbDriver);//添加驱动
    db.setHostName(hostName); //设置主机名
    db.setDatabaseName(dbName); //设置数据库名
    db.setUserName(userName); //设置用户名
    db.setPassword(userPwd); //设置用户密码

    //发送连接
    if(!db.open()) 
    {
        qDebug << db.lastError();
        return false;
    }
    return true;
}

 二、操作数据库

bool queryDB(const QString &sql)
{
    QSqlQuery query;
    query.exec(sql);
    
    if(query.next())
    {
        ...
        return true;
    }
    return false;
}

三、实例

/*
 *功能:一个登录小模块
 *软件环境:ubuntu 9.04, qt4.5, PostgreSQL8.3
 *main.cpp
*/

#include <QApplication>
#include <QtCore/QTextCodec>
#include "login.h"

int main(int argc, char *argv[])
{
	QApplication app(argc, argv);
    QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));

	Login *login = new Login;
	login->show();

	return app.exec();
}

  

/*
 *login.h
 *说明:登录主界面的头文件
*/

#ifndef LOGIN_H
#define LOGIN_H

#include <QDialog>
class QLineEdit;
class QPushButton;

class Login :public QDialog
{
	Q_OBJECT

public:
	Login(QWidget *parent = 0);

public slots:
	void logined();

private:
	QLineEdit *userNameLine;
	QLineEdit *userPwdLine;

	QPushButton *loginButton;
};
#endif

 

/*
 *login.cpp
 *说明:登录主界面
*/
#include <QtGui>
#include "login.h"
#include "mysql.h"

Login::Login(QWidget *parent)
	:QDialog(parent)
{
	QLabel *userNameLabel = new QLabel(tr("用户名:"));
	userNameLine = new QLineEdit;

	QLabel *userPwdLabel = new QLabel(tr("密码:"));
	userPwdLine = new QLineEdit;

	loginButton = new QPushButton(tr("登录"));
	connect(loginButton, SIGNAL(clicked()), this, SLOT(logined()));

	QHBoxLayout *buttonLayout = new QHBoxLayout;
	buttonLayout->addStretch();
	buttonLayout->addWidget(loginButton);

	QGridLayout *mainLayout = new QGridLayout;
	mainLayout->addWidget(userNameLabel, 0, 0);
	mainLayout->addWidget(userNameLine, 0, 1);
	mainLayout->addWidget(userPwdLabel, 1, 0);
	mainLayout->addWidget(userPwdLine, 1, 1);
	mainLayout->addLayout(buttonLayout, 2, 1);
    //mainLayout->addWidget(loginButton, 2, 1);
	setLayout(mainLayout);
	setWindowTitle(tr("登录"));
}

void Login::logined()
{
	QString name = userNameLine->text();
	QString passwd = userPwdLine->text();
    QString sql = "select name, password from users where name = '" 
		+ name + "'and password ='" + passwd + "'";

	MySql mySql;
	if( mySql.queryDB(sql) )
	{
		QMessageBox::information(this, tr("登录成功"),
				tr("登录成功!欢迎进入本系统!"),
				QMessageBox::Ok);
	}
	else
	{
		QMessageBox::warning(this, tr("登录失败"),
				tr("用户名或密码错误!是否重新登录?"),
				QMessageBox::Yes|QMessageBox::No);

	}

}

 

/*
 *mysql.h
 *说明:封装的SQL连接
*/

#ifndef MYSQL_H
#define MYSQL_H

#include <QObject>

class MySql :public QObject
{
public:
	MySql(QObject *parent = 0);

	bool connDB();
	bool queryDB(const QString &sql);

private:
	QString dbDriver;
	QString dbName;
	QString userName;
	QString userPwd;
	QString hostName;
	int hostPort;
};
#endif

 

/*
 *mysql.cpp
 *说明:封装的SQL连接
*/
#include <QtSql>
#include <QSqlDatabase>
#include <QDebug>
#include "mysql.h"

MySql::MySql(QObject *parent)
	:QObject(parent)
{
	dbDriver="QPSQL";   
	dbName="mydb";
	userName="konglingchun";
	userPwd="klcstudy";
	hostName="localhost";
	hostPort=5432;
	connDB();
}

bool MySql::connDB()
{
    QSqlDatabase db = QSqlDatabase::addDatabase(dbDriver);//添加驱动
    db.setHostName(hostName); //设置主机名
    db.setDatabaseName(dbName); //设置数据库名
    db.setUserName(userName); //设置用户名
    db.setPassword(userPwd); //设置用户密码

    //发送连接
    if(!db.open()) 
    {
	//	qDebug() << QSqlDatabase::drivers();
        qDebug() << db.lastError();
        return false;
    }
    return true;
}

bool MySql::queryDB(const QString &sql)
{
    QSqlQuery query;
    query.exec(sql);
    
    if(query.next())
    {
        qDebug() << query.value(0).toString();
        return true;
    }
    return false;
}

 

/*
 *mysql.sql
 *说明:在PostgreSQL数据库中建表用的sql语句
*/
-- DROP TABLE users;

CREATE TABLE users
(
  "name" character varying(20) NOT NULL,
  "password" character varying(20) NOT NULL
)
WITH (OIDS=FALSE);
ALTER TABLE users OWNER TO konglingchun;

insert into users (name, password)
    values ('001', '1234');

 注意:1、在.pro文件中,别忘了加上 QT += sql

          2、如果提示没有PostgrestSQL数据库的驱动,可以通过命令sudo apt-get install libqt4-sql-psql来安装驱动;

               如果您用的是MySQL数据库,那么命令是sudo apt-get install libqt4-sql-mysql。

              我这里有一份很全的QT4的源码包文件,想用哪个库文件直接安装就可以了。

  

Avatar_small
lywdx 说:
2009年10月30日 21:10

恩,很好的实例哈!
学习了!

Avatar_small
孔令春 说:
2009年10月31日 00:20

呵呵,瞎写的,用于入门还行

Avatar_small
boardmodelpaper.com 说:
2024年1月17日 21:46

The Board model paper" typically refers to a sample or model question paper that is designed by educational boards or institutions for various exams. These papers serve as practice material for students preparing for exams, providing them with an idea of the question format, difficulty level, and the type of content that may be covered in the actual examination. boardmodelpaper.com Model papers are usually created for specific subjects or courses. They cover a range of topics and chapters that students are expected to have studied during the academic term. Students often use these educational board model papers as an integral part of their exam preparation strategy, helping them familiarize themselves with the exam pattern and refine their understanding of the subject matter.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter