第一步:安装
qt开发环境
bi@bi-desktop:~$sudo apt-get install qt4-dev-tools qt4-doc qt4-qtconfig qt4-demos qt4-designer
第二步:安装
mysql开发环境
bi@bi-desktop:~$sudo apt-get install mysql-server mysql-client
bi@bi-desktop:~$sudo apt-get install libmysqlclient15-dev
bi@bi-desktop:~$sudo apt-get install libqt4-sql-mysql
bi@bi-desktop:~$sudo /etc/init.d/mysql restart
第三步:给普通用户授权操作数据库
bi@bi-desktop:~$ mysql -u root -p //之后输入密码就可以连接的上了
mysql> create database hanle; (创建一个数据库) //特别要注意后面的分号,最开始我用的时候就吃亏在那个地方
mysql> grant all privileges on *.* to han@localhost identified by '123456';
mysql> quit;
给特定用户分配数据操作权限的格式是:
grant 权限1,权限2, on 数据库名称 表名称 to 用户名@当前主机 ip 地址 identified by '密码';
第四步:测试环境
//注意此步实在创建的QT控制台应用程序
#include <QApplication>
#include <QtSql>
#include <QTableView>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("hanle");
db.sethan("han");
db.setpassword("123456");
db.open();
QSqlQuery query;
query.exec("create table hello(id bigint not null auto_increment,name varchar(255),age
bigint,primary key (id))");
/*query.exec("insert into hello(name, age) values('xiaoxi', 18)");
query.exec("insert into hello(name, age) values('xiaonan', 19)");
query.exec("insert into hello(name, age) values('xiaobei', 20)");
//ODBC
风格
query.prepare("insert into hello(name, age)" "values(?, ?)");
query.addBindValue("xiaoxi");
query.addBindValue(18);
query.exec();
query.addBindValue("xiaonan");
query.addBindValue(19);
query.exec();
query.addBindValue("xiaobei");
query.addBindValue(20);
query.exec();
query.addBindValue("xiaodong");
query.addBindValue(21);
query.exec();
//Oracle
风格
/*query.prepare("insert into hello(name, age) values(:name, :age)");
query.bindValue(":name", "xiaoxi");
query.bindValue(":age", 18);
query.exec();
query.bindValue(":name", "xiaonan");
query.bindValue(":age", 19);
query.exec();
query.bindValue(":name", "xiaobei");
query.bindValue(":age", 20);
query.exec();
query.bindValue(":name", "xiaodong");
query.bindValue(":age", 21);
query.exec();*/
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("select * from hello");
model->setHeaderData(0, Qt::Horizontal, "id");
model->setHeaderData(1, Qt::Horizontal, "name");
model->setHeaderData(2, Qt::Horizontal, "age");
QTableView *view = new QTableView;
view->setWindowTitle("QSqlQueryModel");
view->setModel(model);
view->show();
/*QSqlTableModel *model = new QSqlTableModel;
model->setTable("hello");
model->select();
for (int i = 0; i < model->rowCount(); ++i)
{
QSqlRecord record = model->record(i);
int id = record.value(0).toInt();
QString name = record.value(1).toString();
int age = record.value(2).toInt();
cout << id << " " << qPrintable(name) << " " << age << endl;
}*/
db.close();
return app.exec();
}
编译:
.pro文件里加上下面一行:
QT += sql