QT连接Linux mysql注意

windows:

#define MYSQLDB "QMYSQL"
#define MYSQLDB_HOSTNAME "192.168.228.168"
#define MYSQLDB_NAME "im"
#define MYSQLDB_USERNAME "root"
#define MYSQLDB_PASSWORD "123456"
#define MYSQLDB_PORT 3306

IM_DB_MysqlHelper::IM_DB_MysqlHelper(QWidget *parent/* =0 */,Qt::WFlags/* =0 */)
{
db = QSqlDatabase::addDatabase(MYSQLDB);
db.setHostName(MYSQLDB_HOSTNAME);
db.setDatabaseName(MYSQLDB_NAME);
db.setUserName(MYSQLDB_USERNAME);
db.setPassword(MYSQLDB_PASSWORD);
db.setPort(MYSQLDB_PORT);
}

IM_DB_MysqlHelper::~IM_DB_MysqlHelper()
{

}

/************************************************************************/
/* 成员方法
/************************************************************************/
bool IM_DB_MysqlHelper::CreateConn()
{
if(!db.isValid()){
qDebug() << "not valid!";
return false;
}
else
{
if(db.open())
{
qDebug() << "SUCCEED OPEN DB";
return true;
}
qDebug() << "FAILED TO OPEN DB";
return false;
}
}

bool IM_DB_MysqlHelper::Read(QString sSql)
{
QSqlQuery query;
if(query.exec(sSql)){
while(query.next()){
qDebug() << "id : " << query.value(0).toInt();
qDebug() << "username : " << query.value(1).toString();
qDebug() << "password : " << query.value(2).toString();
}
}
return true;
}

 

 

linux上注意事项:

需要给数据库设置访问权限,起初我认为是端口号不对,vi /etc/my.cnf发现端口是3306

1.进入mysql,输入 mysql -p123456 (密码是123456)

2.设置访问权限

  grant all privileges on im.* to root@'%' identified by '123456';

  grant privileges *.* to root@'%' identified by '123456';

 

发现成功输出:

SUCCEED OPEN DB
id : 1
username : "admin"
password : "111111"
id : 2
username : "cda"
password : "222222"
id : 3
username : "pcupso"
password : "333333"

 

OK,linux上的权限设置是关键

posted @ 2014-03-13 23:52  西山翠冷  阅读(1068)  评论(0编辑  收藏  举报