【Linux】Ubuntu下C語言訪問MySQL數據庫入門,ubuntumysql
使用的系統是Ubuntu 11.10.數據庫是MySQL。
MySQL數據庫環境配置
首先需要安裝MySQL客戶端和服務器,命令行安裝方式為:
[cpp] view plaincopyprint?
- sudo apt-get install mysql-server mysql-client
然後,要使用C語言編程訪問數據庫,需要另外安裝一個開發包:
[cpp] view plaincopyprint?
- sudo apt-get install libmysqlclient15-dev
在MySQL中建立相應數據庫
首先以用戶rick登錄MySQL數據庫(用戶rick已經被root權限用戶賦予了創建數據庫等等的權限):
然後創建一個名為foo的數據庫:
[cpp] view plaincopyprint?
- CREATE DATABASE foo;
然後利用如下SQL語句創建表及插入數據:
[cpp] view plaincopyprint?
- CREATE TABLE children(
- childno int(11) NOT NULL auto_increment,
- fname varchar(30),
- age int(11),
- PRIMARY KEY (childno)
- );
-
- INSERT INTO children(childno,fname,age) VALUES(1,'Jenny',21);
- INSERT INTO children(childno,fname,age) VALUES(2,'Andrew',17);
- INSERT INTO children(childno,fname,age) VALUES(3,'Gavin',8);
- INSERT INTO children(childno,fname,age) VALUES(4,'Duncan',6);
- INSERT INTO children(childno,fname,age) VALUES(5,'Emma',4);
- INSERT INTO children(childno,fname,age) VALUES(6,'Alex',15);
- INSERT INTO children(childno,fname,age) VALUES(7,'Adrian',9);
在MySQL命令行模式中執行方法如下:
MySQL數據庫連接測試
然後采用如下C語言進行數據庫連接測試connect1.c:
[cpp] view plaincopyprint?
- #include <stdlib.h>
- #include <stdio.h>
-
- #include "mysql.h"
-
- int main(int argc,char *argv[])
- {
- MYSQL *conn_ptr;
- conn_ptr = mysql_init(NULL);
-
- if(!conn_ptr)
- {
- fprintf(stderr,"mysql_init failed\n");
- return EXIT_FAILURE;
- }
-
- conn_ptr = mysql_real_connect(conn_ptr,"localhost","rick","rick","foo",0,NULL,0);
-
- if(conn_ptr)
- printf("Connection success\n");
- else
- printf("Connection failed\n");
-
- mysql_close(conn_ptr);
-
- return EXIT_SUCCESS;
- }
執行結果:
注意的是:需要指定include庫和庫文件的路徑名,以及指定鏈接的庫模塊mysqlclient。
如果不在開始的時候安裝開發包,就會產生如下錯誤:
執行SQL語句進行數據操作
向數據庫表children中插入一行:
[cpp] view plaincopyprint?
- #include <stdlib.h>
- #include <stdio.h>
-
- #include "mysql.h"
-
- int main()
- {
- MYSQL my_connecyion;
- int res;
-
- mysql_init(&my_connecyion);
-
- if(mysql_real_connect(&my_connecyion,"localhost","rick","rick","foo",0,NULL,0))
- {
- printf("Connection success\n");
-
- //執行SQL語句
- res = mysql_query(&my_connecyion,"INSERT INTO children(fname,age) VALUES('Ann',3)");
-
- if(!res)
- printf("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(&my_connecyion));
- else
- fprintf(stderr,"Insert error %d : %s \n",mysql_errno(&my_connecyion),mysql_error(&my_connecyion));
-
- mysql_close(&my_connecyion);
- }
- else{
- fprintf(stderr,"Connection failed\n");
- if(mysql_errno(&my_connecyion))
- fprintf(stderr,"Connection error %d : %s\n",mysql_errno(&my_connecyion),mysql_error(&my_connecyion));
- }
-
- return EXIT_SUCCESS;
- }
運行結果:
在這裡特別需要注意的是:
函數mysql_affected_rows返回的是被一個更新操作修改的行數,而不是滿足where子句的行數。