- 论坛徽章:
- 0
|
请教:用Qt库,如何用C++代码实现MySQL的连接(在线等!)
看看这些代码对你有没有启发
- define DRIVER "QMYSQL3" /* see the Qt SQL documentation for a list of available drivers */
- define DATABASE ":dehua:" /* the name of your database */
- define USER "root" /* user name with appropriate rights */
- define PASSWORD "password" /* password for USER */
- define HOST "http://192.168.10.14" /* host on which the database is running */
- bool ServerInfo::connMysql(int csID, QString msg)
- {
- MYSQL mysql;
- char host[32]="localhost";
- char user[32]="root";
- char passwd[32]="password";
- char dbname[32]="dehua";
-
- QString sql;
- if( mysql_init(&mysql) == NULL ) /*初始化数据结构*/
- {
- syslog(LOG_USER|LOG_INFO,"inital mysql handle error\n");
- return FALSE;
- }
- if(mysql_real_connect(&mysql,host,user,passwd,dbname,0,NULL,0) == NULL) /*连接数据库*/
- {
- syslog(LOG_USER|LOG_INFO, "Failed to connect to database: Error: %s\n",mysql_error(&mysql));
- return FALSE;
- }
- msg.replace("'"," "); //去掉单引号
- sql=QString("insert into socRec(socketID,message) values(%1,'%2')")
- .arg(csID)
- .arg(msg); /*构造SQL语句*/
- qWarning(sql);
- if(mysql_query(&mysql,sql) != 0) /*执行SQL语句,进行检索数据*/
- { /*执行SQL语句出错*/
- syslog(LOG_USER|LOG_INFO, "select ps_info Error: %s\n",mysql_error(&mysql));
- qWarning("false");
- }
- else
- {
- qWarning("true");
- }
- }
复制代码 |
|