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 一个库