数据的批量插入:
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <iostream>
#include <QStringList>
#include <QString>
#include <QVariant>
#include <QDebug>
// 逐条插入数据
void InitSQL()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("./database.db");
if (!db.open())
{
std::cout << db.lastError().text().toStdString()<< std::endl;
return;
}
// 执行SQL创建表
db.exec("DROP TABLE Student");
db.exec("CREATE TABLE Student ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL, "
"age INTEGER NOT NULL)"
);
// 逐条插入数据
db.exec("INSERT INTO Student(name,age) ""VALUES ('admin',23)");
db.exec("INSERT INTO Student(name,age) ""VALUES ('zhangsan',25)");
db.exec("INSERT INTO Student(name,age) ""VALUES ('lisi',34)");
// 查询数据
QSqlQuery query("SELECT * FROM Student WHERE age >= 10 AND age <= 100;",db);
QSqlRecord rec = query.record();
// 循环所有记录
while(query.next())
{
// 判断当前记录是否有效
if(query.isValid())
{
int id_ptr = rec.indexOf("id");
int id_value = query.value(id_ptr).toInt();
int name_ptr = rec.indexOf("name");
QString name_value = query.value(name_ptr).toString();
int age_ptr = rec.indexOf("age");
int age_value = query.value(age_ptr).toInt();
qDebug() << "ID: " << id_value << "Name: " << name_value << "Age: " << age_value;
}
}
}
// 多条插入数据
void InitMultipleSQL()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("./database.db");
if (!db.open())
{
std::cout << db.lastError().text().toStdString()<< std::endl;
return;
}
// 执行SQL创建表
db.exec("DROP TABLE Student");
db.exec("CREATE TABLE Student ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL, "
"age INTEGER NOT NULL)"
);
// 批量创建数据
QStringList name_list; name_list << "aa" << "bb" << "cc" ;
QStringList age_list; age_list << "12" << "34" << "45";
// 绑定并插入数据
QSqlQuery query;
query.prepare("INSERT INTO Student(name,age) ""VALUES (:name, :age)");
if(name_list.size() == age_list.size())
{
for(int x=0;x< name_list.size();x++)
{
query.bindValue(":name",name_list[x]);
query.bindValue(":age",age_list[x]);
query.exec();
}
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// InitSQL();
InitMultipleSQL();
return a.exec();
}
使用ListView与TableView配合: 增加槽函数 private slots: void on_currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous);
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <iostream>
#include <QStringList>
#include <QString>
#include <QVariant>
#include <QDebug>
#include <QDataWidgetMapper>
#include <QtSql>
#include <QStandardItem>
#include <QStringList>
#include <QStringListModel>
QSqlQueryModel *qryModel; // 数据模型
QItemSelectionModel *theSelection; // 选择模型
QDataWidgetMapper *dataMapper; // 数据界面映射
// 多条插入数据
void InitMultipleSQL()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("./database.db");
if (!db.open())
{
std::cout << db.lastError().text().toStdString()<< std::endl;
return;
}
// 执行SQL创建表
db.exec("DROP TABLE Student");
db.exec("CREATE TABLE Student ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL, "
"age INTEGER NOT NULL)"
);
// 批量创建数据
QStringList name_list; name_list << "zhangsan" << "lisi" << "wangwu";
QStringList age_list; age_list << "25" << "34" << "45";
// 绑定并插入数据
QSqlQuery query;
query.prepare("INSERT INTO Student(name,age) ""VALUES (:name, :age)");
if(name_list.size() == age_list.size())
{
for(int x=0;x< name_list.size();x++)
{
query.bindValue(":name",name_list[x]);
query.bindValue(":age",age_list[x]);
query.exec();
}
}
// ------------------------------------------------
// 创建第二张表,与第一张表通过姓名关联起来
db.exec("DROP TABLE StudentAddressList");
db.exec("CREATE TABLE StudentAddressList("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL, "
"address VARCHAR(128) NOT NULL"
")");
db.exec("INSERT INTO StudentAddressList(name,address) VALUES ('zhangsan','192.168.1.1')");
db.exec("INSERT INTO StudentAddressList(name,address) VALUES ('zhangsan','192.168.1.2')");
db.exec("INSERT INTO StudentAddressList(name,address) VALUES ('zhangsan','192.168.1.3')");
db.exec("INSERT INTO StudentAddressList(name,address) VALUES ('lisi','192.168.10.10')");
db.exec("INSERT INTO StudentAddressList(name,address) VALUES ('lisi','192.168.10.11')");
db.exec("INSERT INTO StudentAddressList(name,address) VALUES ('wangwu','192.168.100.100')");
}
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{
ui->setupUi(this);
InitMultipleSQL();
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("./database.db");
if (!db.open())
{
std::cout << db.lastError().text().toStdString()<< std::endl;
return;
}
// 查询数据表中记录
qryModel=new QSqlQueryModel(this);
qryModel->setQuery("SELECT * FROM Student ORDER BY id");
if (qryModel->lastError().isValid())
{
return;
}
// 设置TableView表头数据
qryModel->setHeaderData(0,Qt::Horizontal,"ID");
qryModel->setHeaderData(1,Qt::Horizontal,"Name");
qryModel->setHeaderData(2,Qt::Horizontal,"Age");
// 将数据绑定到模型上
theSelection=new QItemSelectionModel(qryModel);
ui->tableView->setModel(qryModel);
ui->tableView->setSelectionModel(theSelection);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
// 创建数据映射
dataMapper= new QDataWidgetMapper();
dataMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
dataMapper->setModel(qryModel);
dataMapper->addMapping(ui->lineEdit_id,0);
dataMapper->addMapping(ui->lineEdit_name,1);
dataMapper->addMapping(ui->lineEdit_age,2);
dataMapper->toFirst();
// 绑定信号,当鼠标选择时,在底部编辑框中输出
connect(theSelection,SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),this,SLOT(on_currentRowChanged(QModelIndex,QModelIndex)));
}
// 鼠标点击后的处理槽函数
void MainWindow::on_currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
Q_UNUSED(previous);
if (!current.isValid())
{
return;
}
dataMapper->setCurrentModelIndex(current);
// 获取到记录开头结尾
bool first=(current.row()==0); // 是否首记录
bool last=(current.row()==qryModel->rowCount()-1);// 是否尾记录
std::cout << "IsFirst: " << first << "IsLast: " << last << std::endl;
// 获取name字段数据
int curRecNo=theSelection->currentIndex().row(); // 获取当前行号
QSqlRecord curRec=qryModel->record(curRecNo); // 获取当前记录
QString uname = curRec.value("name").toString();
std::cout << "Student Name = " << uname.toStdString() << std::endl;
// 查StudentAddressList表中所有数据
// 根据姓名过滤出该用户的所有数据
QSqlQuery query;
query.prepare("select * from StudentAddressList where name = :x");
query.bindValue(":x",uname);
query.exec();
// 循环获取该用户的数据,并将address字段提取出来放入QStringList容器
QSqlRecord rec = query.record();
QStringList the_data;
while(query.next())
{
int index = rec.indexOf("address");
QString data = query.value(index).toString();
std::cout << "User Address = " << data.toStdString() << std::endl;
the_data.append(data);
}
// 关联到ListView数据表中
QStringListModel *model;
model = new QStringListModel(the_data);
ui->listView->setModel(model);
}
MainWindow::~MainWindow()
{
delete ui;
}