一步步学Qt,第十天-MYSQL数据库操作

一步步学Qt,第十天-MYSQL数据库操作


Qt连接数据库Mysql的办法可以查看:一步步学Qt.第二天-续集-mysql连接成功


今天写了一个连接数据库的demo,我把数据库操作与数据展示独立开了,也差不多就是Qt里面所说的Model/View模式。具体看下面:

数据表:

在windows cmd中查看


图示分析:
1、登录mysql的方法:mysql -u "username" -p [return]
*return 就是回车
还记得Qt的回车事件么???》》》Qt::Key_Return
2、选择数据库:use databasename
3、查看数据表:show tables;
4、查看数据表的结构:desc tablename;

程序完整code
#ifndef DATABASELAYER_H
#define DATABASELAYER_H
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlTableModel>

class DataBaseLayer
{
public:
    DataBaseLayer();
    bool dbopen();
    void dbclose();
    QSqlTableModel* getViewTableModel(QString table);
private:
    QSqlDatabase db;
};

#endif // DATABASELAYER_H

#include <QSqlTableModel>
#include "databaselayer.h"

DataBaseLayer::DataBaseLayer()
{
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setDatabaseName("test");
    db.setUserName("root");
    db.setPassword("admin");
}

bool DataBaseLayer::dbopen()
{
    return db.open();
}

void DataBaseLayer::dbclose()
{
     db.close();
}

QSqlTableModel*  DataBaseLayer::getViewTableModel(QString table)
{
    QSqlTableModel *model = new QSqlTableModel;
    model->setTable(table);
    model->setSort(0,Qt::AscendingOrder);
    model->setHeaderData(0,Qt::Horizontal,"Name");
    model->setHeaderData(1,Qt::Horizontal,"Sex");
    model->setHeaderData(2,Qt::Horizontal,"age");
    model->select();
    return model;
}

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QSqlTableModel>
#include "databaselayer.h"

namespace Ui {
    class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
    void on_Widget_destroyed();

private:
    Ui::Widget *ui;
    DataBaseLayer *db;
    QSqlTableModel *model;
    void closeEvent(QCloseEvent *);
};

#endif // WIDGET_H



#include "widget.h"
#include "ui_widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    db = new DataBaseLayer;
    QString table = "qt_user";
    model = db->getViewTableModel(table);
    ui->tableView->setModel(model);
}

Widget::~Widget()
{
    delete ui;
    delete db;
}

void Widget::closeEvent(QCloseEvent *)
{
    db->dbclose();
}


#-------------------------------------------------
#
# Project created by QtCreator 2011-09-02T12:20:44
#
#-------------------------------------------------

QT       += core gui
QT       +=sql

TARGET = sql
TEMPLATE = app


SOURCES += main.cpp\
        widget.cpp \
    databaselayer.cpp

HEADERS  += widget.h \
    databaselayer.h

FORMS    += widget.ui


在数据库中添加数据信息:



分析:

SQL的insert into数据插入语句insert into tablename values(value1,value2,..);

*当您的数据表的字段使用varchar类型的时候,value*记得加上‘’哦,eg:insert into qt_user('hello','girl',10);


程序运行效果:



posted @ 2011-09-02 16:51  Podevor  阅读(495)  评论(0编辑  收藏  举报