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的代码实现)