1.首先要下载qt create
官网链接:https://wiki.qt.io/Main
2.下载mysql驱动mysql-connector-c,注意是c或c++版本的驱动
官网下载地址:https://dev.mysql.com/downloads/connector/
3.将连接的libmysql.dll加入到qt的安装bin目录下如我的就是:
D:QTTqtsoft5.4mingw491_32in
4.由于QT5.4以上支持mysql驱动,也提供了API所以用起来也很方便
配置文件引入:
QT += core gui sql
5.代码,插入数据,头文件
#include<QSqlDatabase> #include<QtSql> namespace Ui { class SqlWidget; } class SqlWidget : public QWidget { Q_OBJECT public: explicit SqlWidget(QWidget *parent = 0); ~SqlWidget(); void InitData(); void InitUI(); void InitConnet(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); void on_pushButton_3_clicked(); private: Ui::SqlWidget *ui; QSqlTableModel *m_Model; QSqlDatabase db; }; #endif // SQLWIDGET_H
6.源文件
#include "sqlwidget.h" #include "ui_sqlwidget.h" SqlWidget::SqlWidget(QWidget *parent) : QWidget(parent), ui(new Ui::SqlWidget) { ui->setupUi(this); InitData(); } SqlWidget::~SqlWidget() { delete ui; } void SqlWidget::InitData() { /**常见数据库驱动 QSQLITE ,QODBC,QPLSQL,SMYSQL***/ db = QSqlDatabase::addDatabase("QMYSQL");//加入mysql数据库 db.setHostName("localhost"); db.setDatabaseName("db"); //打开数据库 if(db.open("root","123456")==false) { ui->connectstate_lb->setText("连接失败!"); return; } ui->connectstate_lb->setText("连接成功!"); db.exec("create table tb2(eid vchar[10] not null,times vchar[10] not null, feedspeed float not null, )ENGINE=InnoDB DEFAULT CHARSET=utf8"); } void SqlWidget::InitUI() { } void SqlWidget::InitConnet() { } void SqlWidget::on_pushButton_clicked() { m_Model = new QSqlTableModel; m_Model->setTable("ss"); m_Model->setHeaderData(0,Qt::Horizontal,"eqid"); m_Model->setHeaderData(1,Qt::Horizontal,"time"); m_Model->setHeaderData(2,Qt::Horizontal,"feedspeed"); m_Model->setEditStrategy(QSqlTableModel::OnManualSubmit); } void SqlWidget::on_pushButton_2_clicked() { if(db.isValid()) { db.close(); } } void SqlWidget::on_pushButton_3_clicked() { QSqlRecord rd = m_Model->record(); rd.setValue("eqid",ui->eqid_le->text().trimmed()); rd.setValue("time",ui->time_le->text().trimmed()); rd.setValue("feedspeed",ui->dsb->value()); m_Model->insertRecord(-1,rd); m_Model->submitAll(); }