本地
learned
- .pro +sql
- QSqlDatabase::addDatabase(“NAME”)加载数据库
- QSqlquery::exec执行sql命令,返回true或false
- QString的拼接 .arg()
1
| QString sql=QString("insert into student values (%1,'%2','%3');)").arg(id).arg(name).arg(birthday);
|
code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| #include "widget.h" #include "ui_widget.h" #include <QMessageBox> #include <QSqlQuery>
Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this);
db = QSqlDatabase::addDatabase("QMYSQL"); db.setDatabaseName("mydatabase"); db.setHostName("localhost"); db.setUserName("root"); db.setPassword("ljn20040118@@");
qDebug()<<QSqlDatabase::drivers(); if(db.open()) { QMessageBox::information(this,"连接提示","连接成功"); } else{ QMessageBox::warning(this,"连接提示","连接失败"); } }
Widget::~Widget() { delete ui; }
void Widget::on_insertButton_clicked() { QString id = ui->numberEdit->text(); QString name = ui->numberEdit->text(); QString birthday = ui->birthdayEdit->text();
QString sql=QString("insert into student values (%1,'%2','%3');)").arg(id).arg(name).arg(birthday);
QSqlQuery query; if(query.exec(sql)) { QMessageBox::information(this,"插入提示","插入成功"); } else { QMessageBox::warning(this,"插入提示","插入失败"); }
}
void Widget::on_findButton_clicked() { QSqlQuery query; query.exec("select * from student"); while(query.next()) { qDebug()<<query.value(0);
} }
|
网络
learned
QSqlTableModel::->select方法+QTableView组件->setModel 方便显示
code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| #include "widget.h" #include "ui_widget.h" #include <QMessageBox>
Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("192.168.217.129"); db.setDatabaseName("mydatabase"); db.setUserName("test0"); db.setPassword("ljn20040118LJN@@");
if(db.open()) { QMessageBox::information(this,"连接提示","连接成功");
m=new QSqlTableModel(); m->setTable("student"); ui->tableView->setModel(m); } else { QMessageBox::warning(this,"连接提示","连接失败"); } }
Widget::~Widget() { delete ui; }
void Widget::on_pushButton_clicked() { m->select(); }
|