C语言连接mysql数据库实现insert语句:
数据库:test
表:systeminfo
CREATE TABLE `systeminfo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ip_info` varchar(50) NOT NULL,
`serv_info` varchar(50) NOT NULL,
`cpu_info` varchar(50) NOT NULL,
`disk_info` varchar(50) NOT NULL,
`mem_info` varchar(50) NOT NULL,
`load_info` varchar(50) NOT NULL,
`mark_info` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ip_info` (`ip_info`),
UNIQUE KEY `ip_info_2` (`ip_info`)
);
/* insert.c */ #include <stdio.h> #include <stdlib.h> #include "/usr/include/mysql/mysql.h" /*注意哦,上面必须是mysql.h的绝对地址,一般在mysql下的include目录下,仔细看看你的在哪里?*/ int main(int argc, char *argv[]) { MYSQL my_connection; int res; mysql_init(&my_connection); /*mysql_real_connect(&mysql,host,user,passwd,dbname,0,NULL,0) == NULL)*/ ,NULL,CLIENT_FOUND_ROWS)) { printf("Connection successn"); res = mysql_query(&my_connection, "insert into systeminfo values(null,'y1','y2','y3','y4','y5','y6','y7');"); if (!res) { printf("Inserted %lu rowsn",(unsigned long)mysql_affected_rows(&my_connection)); /*里头的函数返回受表中影响的行数*/ } else { //分别打印出错误代码及详细信息 fprintf(stderr, "Insert error %d: %sn",mysql_errno(&my_connection),mysql_error(&my_connection)); } mysql_close(&my_connection); } else { fprintf(stderr, "Connection failedn"); if (mysql_errno(&my_connection)) { fprintf(stderr, "Connection error %d: %sn",mysql_errno(&my_connection),mysql_error(&my_connection)); } } }
insert.c
编译时添加-L/usr/lib64/mysql -lmysqlclient 参数
# gcc insert.c -L/usr/lib64/mysql -lmysqlclient -o insert
更新语句时即可以将insert语句改为update。
res = mysql_query(&my_connection, "update systeminfo set sex='男' where id<5 ");