ubuntu10.10下qt连接mysql数据库

ubuntu10.10下qt连接mysql数据库
2011-01-24 11:22

第一步:安装qt开发环境

xhy@xhy-desktop:~$sudo apt-get install qt4-dev-tools qt4-doc qt4-qtconfig qt4-demos qt4-designer

第二步:安装mysql开发环境

xhy@xhy-desktop:~$sudo apt-get install mysql-server mysql-client

xhy@xhy-desktop:~$sudo apt-get install libmysqlclient15-dev

xhy@xhy-desktop:~$sudo apt-get install libqt4-sql-mysql

xhy@xhy-desktop:~$sudo /etc/init.d/mysql restart

 

第三步:给普通用户授权操作数据库
xhy@xhy-desktop:~$ mysql -u root -p      (root登录数据库)
mysql> create database mydb;                     (创建一个数据库)
mysql> grant all privileges on *.* to username@localhost identified by 'password';
mysql> quit;
给特定用户分配数据操作权限的格式是:
grant 权限1,权限2,...权限n on 数据库名称.表名称 to 用户名@用户ip地址 identified by '密码';

 

 第四步:测试环境

#include #include #include #include using namespace std; int main(int argc, char *argv[]) { QApplication app(argc, argv); QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("localhost"); db.setDatabaseName("mydb"); db.setUserName("username"); db.setPassword("password"); 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)"); query.exec("insert into hello(name, age) values('xiaodong', 21)"); 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(); db.close(); return app.exec(); }

编译:

xhy@xhy-desktop:~$ qmake -project

xhy@xhy-desktop:~$ qmake

一定别忘了在工程的.pro文件里加上下面一行:

QT += sql

xhy@xhy-desktop:~$make

xhy@xhy-desktop:~$./mysql

 

你可能感兴趣的:(Qt,初识Qt,mysql,qt,ubuntu,数据库,insert,database)