c语言连接mysql——insert的代码实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c语言连接mysql——insert的代码实现相关的知识,希望对你有一定的参考价值。

//mysql_insert
//gcc mysql_insert.c -o test -I /usr/include/mysql -L /usr/lib -lmysqlclient

#include <stdio.h>
#include <mysql/mysql.h>
#include <string.h>

#define HOST "localhost"
#define USERNAME "SERVER"
#define PASSWORD "SERVER_PASSWORD"
#define DATABASE "remote_control"

int main()
{
char device_id[12] = "12345678901x";
char device_mac[20] = "12345678901234567890";
char device_nikname[20] = "12345678901234567890";
char device_online_status[1] = "1";
char device_switch_status[1] = "1";
char dstr[107];
char *insert_device_sql = &dstr[0];

strcpy (dstr, "insert into devices values(‘");
strcat (dstr, device_id);
strcat (dstr, "‘,‘");
strcat (dstr, device_mac);
strcat (dstr, "‘,‘");
strcat (dstr, device_nikname);
strcat (dstr, "‘,‘");
strcat (dstr, device_online_status);
strcat (dstr, "‘,‘");
strcat (dstr, device_switch_status);
strcat (dstr, "‘)");
//printf("insert_device_sql =%d\n", (int)strlen(dstr));
//char *insert_device_sql = "insert into devices values(‘‘,‘‘,‘‘,‘‘,‘‘)";

char user_id[12] = "123456789012";
char user_account[11] = "12345678901";
char user_password[8] = "12345678";
char user_online_status[1] = "1";
char ustr[82];
char *insert_user_sql = &ustr[0];

strcpy (ustr, "insert into users values(‘");
strcat (ustr, user_id);
strcat (ustr, "‘,‘");
strcat (ustr, user_account);
strcat (ustr, "‘,‘");
strcat (ustr, user_password);
strcat (ustr, "‘,‘");
strcat (ustr, user_online_status);
strcat (ustr, "‘)");
//printf("insert_user_sql= %d\n", (int)strlen(ustr));
//char *insert_user_sql = "insert into user values(‘‘,,‘‘,‘‘)";

//char *sql = insert_device_sql;
char *sql = insert_user_sql;

MYSQL my_connection;
mysql_init(&my_connection);/*初始化mysql连接my_connection*/

if (!mysql_real_connect(&my_connection, HOST, USERNAME, PASSWORD, DATABASE, 0, NULL, CLIENT_FOUND_ROWS))
{/*连接失败*/
printf("数据库连接失败: %s\n", mysql_error(&my_connection));
return 0;
}

mysql_query(&my_connection, "set names utf8");/*设置编码为utf8*/

int res;
res = mysql_real_query(&my_connection, sql, (unsigned int)strlen(sql));
if (res)
{/*执行失败*/
printf("sql語句执行失败: %s\n", mysql_error(&my_connection));
mysql_close(&my_connection);
return 0;
}

printf("数据插入成功!\n");
printf("%d行数据受到影响!\n", (int)mysql_affected_rows(&my_connection));

mysql_close(&my_connection);

return 0;
}

以上是关于c语言连接mysql——insert的代码实现的主要内容,如果未能解决你的问题,请参考以下文章

c语言怎么连接mysql数据库 代码

如何用C语言连接MYSQL数据库

php mysql_insert_id()

c语言调用数据库mysql5.6,数据查询后怎样读取

用C语言怎么实现与数据库的连接

C或C++语言连接ACCESS数据库代码是啥