1. 程式人生 > >Linux--C語言操作資料庫(一)插入資料

Linux--C語言操作資料庫(一)插入資料

 各種渠道去找有關於使用C語言操作資料庫的資料,好辛苦,弄出來了!

資料庫部分

首先建立一張表

create table children(childno int not null unique,fname varchar(20),age int);

這裡寫圖片描述
然後插入一組資料

insert into children values(1,'yuanlief',23);

這裡寫圖片描述
查詢

select *from children;

這裡寫圖片描述

資料庫搞定,接下來是C語言部分。

C語言部分

insert.c 全部原始碼。

/* insert.c */
#include <stdio.h>
#include <stdlib.h> #include <mysql/mysql.h> int main(int argc, char *argv[]) { MYSQL my_connection; int res; mysql_init(&my_connection); /*mysql_real_connect(&mysql,主機名,使用者名稱,密碼,資料庫名,0,NULL,0) == NULL)*/ /*mysql_real_connect(&mysql,host,user,passwd,dbname,0,NULL,0) == NULL)*/
if (mysql_real_connect(&my_connection, "localhost", "root", "123456","test",0,NULL,CLIENT_FOUND_ROWS)) { printf("Connection success\n"); res = mysql_query(&my_connection, "insert into children values(2,'yuanlifu',24)"); if (!res) { printf
("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(&my_connection)); /*裡頭的函式返回受表中影響的行數*/ } else { //分別打印出錯誤程式碼及詳細資訊 fprintf(stderr, "Insert error %d: %s\n",mysql_errno(&my_connection),mysql_error(&my_connection)); } mysql_close(&my_connection); } else { fprintf(stderr, "Connection failed\n"); if (mysql_errno(&my_connection)) { fprintf(stderr, "Connection error %d: %s\n",mysql_errno(&my_connection),mysql_error(&my_connection)); } } return 1;// "EXIT_SUCCES"; }

然後編譯

gcc -o insert insert.c

爆出大量未定義識別符號的錯誤!應該是GCC編譯器沒有找到標頭檔案。
這裡寫圖片描述

各種糾結,不知怎麼辦。。。。。。
這裡省略三千字糾結!
從一位大神那裡找到這個解決辦法,編譯成功!

gcc -o insert insert.c -lmysqlclient -I/usr/include/mysql -L/usr/lib64/mysql

但是這個也可以編譯

gcc -o insert insert.c -lmysqlclient -L/usr/lib64/mysql

這兩個字尾缺一不可!

執行:

./insert

這裡寫圖片描述

檢視一下資料庫:

select *from children;

這裡寫圖片描述

插入成功!