ubuntu下c語言對mysql進行CRUD(增刪改查)
阿新 • • 發佈:2018-11-19
Step 1:登入mysql
mysql -u root -p
Step 2:在資料庫中新增資料:
create database foo;
use foo;
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);
Step 3:測試連線,編寫connect.c檔案
#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","root","xxxxxx","foo",0,NULL,0);
if(conn_ptr)
printf("Connection success\n");
else
printf("Connection failed\n");
mysql_close(conn_ptr);
return EXIT_SUCCESS;
}
執行如下命令
gcc -I/usr/include/mysql connect.c -L/usr/lib/mysql -lmysqlclient -o connect
./connect
Step 4:向資料庫中增加一條資料
#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","root","xxxxxx","foo",0,NULL,0)) {
printf("Connection success\n");
//執行SQL語句
res = mysql_query(&my_connecyion,"INSERT INTO children(fname,age) VALUES('ceh',10000)");
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;
}
執行結果
Step 5:另附一個功能更強的訪問mysql程式:
use foo;
create table tbStu(
id int not null auto_increment primary key,
name varchar(10) not null,
score int not null
);
describe tbStu;
insert into tbStu(id, name, score) values(1, "xiaobinge",100);
insert into tbStu(id, name, score) values(2, "lippman",88);
insert into tbStu(id, name, score) values(3, "Meyers",94);
insert into tbStu(id, name, score) values(4, "stevens",102);
insert into tbStu(id, name, score) values(5, "alex",8);
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // 用於支援strlen
#include <mysql.h>
MYSQL* pConn; // 連線物件
MYSQL_RES* pRes; // 結果集
MYSQL_ROW Row; // 記錄,注意不是MYSQL_ROW * 指標型別
struct Stu // 學生結構體
{
int id; // 學號
char name[10]; // 姓名
int score; // 分數
};
/* 增加(插入)一條記錄 */
void add_record()
{
char cmd[1024] = {0};
int i = 0, numFields = 0;
int ret = 0;
struct Stu stu;
printf("請輸入學生id:");
scanf("%d", &stu.id);
printf("請輸入學生姓名:");
scanf("%s", stu.name);
printf("請輸入學生分數:");
scanf("%d", &stu.score);
// 強大的sprintf為使用者減少輸入 ,避免讓使用者輸入完整的命令,而只需要記錄的資料輸入
sprintf(cmd, "insert into tbStu(id,name,score) values(%d,'%s',%d)",stu.id,stu.name,stu.score);
ret = mysql_real_query(pConn, cmd, (unsigned int)strlen(cmd));
if(! ret) // ret = 0是表示正確
{
// 列印受到影響的行的個數
printf("Inserted by %lu rows\n",(unsigned long)mysql_affected_rows(pConn));
}
else // ret != 0 表示出錯
{
// 打印出錯及相關資訊
fprintf(stderr, "Insert error %d:%s\n", mysql_errno(pConn), mysql_error(pConn));
}
// mysql_free_result(pRes);
return ;
}
/* 刪除一條記錄 */
void del_record()
{
int i = 0,numFields = 0;
int ret = 0;
char cmd[1024] = {0};
int delId;
printf("請輸入要刪除的學生id:");
scanf("%d",&delId);
sprintf(cmd,"delete from tbStu where id = %d",delId);
ret = mysql_real_query(pConn, cmd, (unsigned int)strlen(cmd));
if(! ret) // ret = 0是表示正確
{
// 列印受到影響的行的個數
printf("Deleted by %lu rows\n",(unsigned long)mysql_affected_rows(pConn));
}
else
{
// 打印出錯及相關資訊
fprintf(stderr, "Deleted error %d:%s\n", mysql_errno(pConn), mysql_error(pConn));
}
// mysql_free_result(pRes);
return ;
}
/* 修改一條key指定的記錄 */
void mod_record()
{
int i = 0,numFields = 0;
int ret = 0;
char cmd[1024] = {0};
struct Stu stu;
int modId;
printf("請輸入要修改的學生id:");
scanf("%d", &modId);
printf("請輸入該學生的新id:");
scanf("%d", &stu.id);
printf("請輸入該學生的新姓名:");
scanf("%s", stu.name);
printf("請輸入學生新分數:");
scanf("%d", &stu.score);
sprintf(cmd,"update tbStu set id=%d,name='%s',score=%d where id=%d",stu.id,stu.name,stu.score,modId);// 注意%s兩邊有小引號哦
ret = mysql_real_query(pConn, cmd, (unsigned int)strlen(cmd));
if(! ret) // ret = 0是表示正確
{
// 列印受到影響的行的個數
printf("Updated by %lu rows\n",(unsigned long)mysql_affected_rows(pConn) );
}
else
{
// 打印出錯及相關資訊
fprintf(stderr, "Updated error %d:%s\n", mysql_errno(pConn), mysql_error(pConn));
}
// mysql_free_result(pRes);
return ;
}
/* 列印整張表格 */
void display_record()
{
int i = 0,numFields = 0;
int ret = 0;
char cmd[1024] = {0};
sprintf(cmd,"select* from tbStu"); // 整張表查詢
ret = mysql_real_query(pConn, cmd, (unsigned int)strlen(cmd));
if(ret) // 出錯
{
printf("select error:%s\n", mysql_error(pConn));
}
else
{
pRes = mysql_store_result(pConn);
if(pRes)
{
printf("一共%d行\n",(int)mysql_num_rows(pRes));
numFields = mysql_num_fields(pRes); // 獲取列的個數
while(Row = mysql_fetch_row(pRes)) // 取出每條記錄
{
for(i = 0; i < numFields; i++)
{
printf("%s\t",Row[i]?Row[i]:NULL);
}
printf("\n");
}
if(mysql_errno(pConn))
{
fprintf(stderr, "Retrieve error:%s\n", mysql_error(pConn));
}
}
}
// mysql_free_result(pRes);
return ;
}
/* 按成績降序排序 */
void sort_desc()
{
int i = 0, numFields = 0;
int ret = 0;
char cmd[1024] = {0};
sprintf(cmd,"select* from tbStu order by score desc");
ret = mysql_real_query(pConn, cmd, (unsigned int)strlen(cmd));
if(ret) // 出錯
{
printf("select error:%s\n", mysql_error(pConn));
}
else
{
pRes = mysql_store_result(pConn);
if(pRes)
{
printf("一共%d行\n",(int)mysql_num_rows(pRes));
numFields = mysql_num_fields(pRes); // 獲取列的個數
while(Row = mysql_fetch_row(pRes)) // 取出每條記錄
{
for(i = 0; i < numFields; i++)
{
printf("%s \t",Row[i]?Row[i]:NULL);
}
printf("\n");
}
if(mysql_errno(pConn))
{
fprintf(stderr, "Retrieve error:%s\n", mysql_error(pConn));
}
}
}
// mysql_free_result(pRes);
return ;
}
int main()
{
pConn = mysql_init(NULL);
if(!pConn)
{
printf("pConn初始化失敗\n");
return -1;
}
else
{
printf("pConn初始化成功\n");
}
pConn = mysql_real_connect(pConn, "localhost", "root", "xxxxxx", "foo", 0, NULL, 0);
if(!pConn)
{
printf("pConn連線失敗\n");
return -1;
}
else
{
printf("pConn連線成功\n");
}
while(1)
{
printf("******1.增加一條記錄***********\n");
printf("******2.刪除一條記錄***********\n");
printf("******3.修改一條記錄***********\n");
printf("******4.查詢現在的所有記錄*****\n");
printf("******5.按成績降序排序*********\n");
printf("******0.退出程式***************\n");
printf("請輸入操作選項編號0~5:");
int id;
scanf("%d",&id);
switch(id)
{
case 0:
{
printf("Bye");
mysql_free_result(pRes);
mysql_close(pConn);
return 0;
}
case 1:
{
add_record();
break;
}
case 2:
{
del_record();
break;
}
case 3:
{
mod_record();
break;
}
case 4:
{
display_record();
break;
}
case 5:
{
sort_desc();
break;
}
}// end switch
}// end while
return 0;
}
執行結果如下:
ps
1.c99 之前的C語言不能出現bool變數,編譯不過的。在c99之後如果用了bool變數,加#include <stdbool.h>也可以解決。
2.mysql_free_result(pRes); 不能重複呼叫。(這個也沒仔細測試,反正寫在每個操作的return 之前,偶爾有時會提示,出現多次釋放指標問題)
3.空指標不是null,而是大寫的NULL.
4.只有一個.c檔案,所以直接用gcc 編譯,不需要麻煩的make。
gcc adus.c -o adus -I /usr/include/mysql/ -L /usr/lib/mysql/ -l mysqlclient
分別是大寫的i,表示INCLUDE,大寫的L,表示LINK,小寫的L,表示link 一個庫