c串連mysql的執行個體

來源:互聯網
上載者:User
mysql 今天給新來的同事做mysql培訓,用到的一個例子:
串連資料庫test 使用者名稱root密碼abc
在裡面有一個username的表,describe username結果如下
mysql> describe username;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(10) | YES | | NULL | |
| username | varchar(32) | | PRI | | |
+----------+-------------+------+-----+---------+-------+

mysql> select * from username;
+------+----------+
| id | username |
+------+----------+
| 1 | sfs |
+------+----------+
1 row in set (0.00 sec)


本文目的尋找執行select id from username這個語句並列印結果
代碼:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
MYSQL mysql;
main()
{
   char host[32]="localhost";
   char user[32]="root";
   char passwd[32]="abc";
   char dbname[32]="test";   
   
   if( mysql_init(&mysql) == NULL )
   {
      syslog(LOG_USER|LOG_INFO,"inital mysql handle errorn");
      return 1;
   }
   if (mysql_real_connect(&mysql,host,user,passwd,dbname,0,NULL,0) == NULL)
   {
      syslog(LOG_USER|LOG_INFO, "Failed to connect to database: Error: %sn",mysql_error(&mysql));
      return 1;
   }
   else syslog(LOG_USER|LOG_INFO, "connect to database: n");
   find_ps();   
   db_close();
   return 0;
}
int db_close()
{
        mysql_close(&mysql);
         return 0;
}


int  find_ps ()
{
   MYSQL_ROW m_row;
   MYSQL_RES *m_res;
   char sql[1024],username[32];
   int res=1;
   int *id;
   sprintf(sql,"select id from username");
   if(mysql_query(&mysql,sql) != 0)
   {
      syslog(LOG_USER|LOG_INFO, "select ps_info Error: %sn",mysql_error(&mysql));
      return res;
   }
   m_res = mysql_store_result(&mysql);
   if(m_res==NULL)
   {
      syslog(LOG_USER|LOG_INFO, "select username Error: %sn",mysql_error(&mysql));
      res = 3;
      return res;
   }
   if(m_row = mysql_fetch_row(m_res))
   {
      printf("m_row=%dn",atoi(m_row[0]));
      res = 0;      
   }
   mysql_free_result(m_res);
   return res;
}

編譯命令
gcc -g connect_db.c -L/usr/lib/mysql -lmysqlclient -lz
注意:
如果/tmp/ccTGmMS21.o: In function `main':
/tmp/ccTGmMS21.o(.text+0x11): undefined reference to `mysql_init'
那麼參數增加-L/usr/lib/mysql -lmysqlclient
如果
usr/lib/mysql/libmysqlclient.a(my_compress.o): In function `my_uncompress':
my_compress.o(.text+0xaa): undefined reference to `uncompress'
那麼增加-lz參數


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.