数据库上手避坑之--向特定的表插入数据
代码sqlInsertData.c
1 /* *=+=+=+=+* *** *=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= 2 * 作者代号: *** :guochaoxxl 3 * 版权声明: *** :(魎魍魅魑)GPL3 4 * 联络信箱: *** :guochaoxxl@163.com 5 * 文档用途: *** :深入理解C指针 6 * 文档信息: *** :~/WORKM/sqlInserData.c 7 * 修订时间: *** :2020年第47周 11月23日 星期一 下午09:13 (328天) 8 * 代码说明: *** :自行添加 9 * *+=+=+=+=* *** *+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+*/ 10 #include<stdio.h> 11 #include<mysql/mysql.h> 12 13 #define USER "gsc" 14 #define PWD "××××××" 15 #define DATABASENAME "student_info" 16 #define TABLENAME "stu_info" 17 18 typedef struct _stu 19 { 20 int stuId; 21 char stuName[40]; 22 char gender[10]; 23 int phone; 24 char email[40]; 25 char account[40]; 26 char code[40]; 27 int adminId; 28 } Stu; 29 30 int main(int argc, char **argv) 31 { 32 //定义句柄 33 MYSQL conn; 34 35 //初始化句柄 36 if(NULL == mysql_init(&conn)) 37 { 38 printf("mysql init error!\n"); 39 return -1; 40 } 41 42 if(NULL == mysql_real_connect(&conn,"localhost",USER, PWD, DATABASENAME,0,NULL,0)) 43 { 44 printf("%s\n", mysql_error(&conn)); 45 return -1; 46 } 47 48 printf("连接数据库成功!\n"); 49 50 //设置字符集 51 mysql_set_character_set(&conn,"utf8"); 52 char sql[512]; 53 Stu s1={101,"张三","女",13307921111,"zhangsan@163.com","zhangsan","110066", 901}; 54 sprintf(sql, "insert into stu_info values(%d,'%s','%s',%d,'%s','%s','%s',%d)",s1.stuId,s1.stuName,s1.gender,s1.phone,s1.email,s1.account,s1.code,s1.adminId); 55 56 if(0 != mysql_query(&conn,sql)) 57 { 58 printf("%s\n",mysql_error(&conn)); 59 return -1; 60 } 61 printf("数据插入成功!\n"); 62 mysql_close(&conn); 63 64 return 0; 65 }
Makefile文件:
sqlInserData:sqlInserData.c
gcc -Wall -g -I/usr/include/mariadb -o sqlInserData sqlInserData.c -lmysqlclient
运行结果:
连接数据库成功!
数据插入成功!
进入数据库查看:
mysql -ugsc -p Enter password: Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 4 Server version: 10.5.8-MariaDB Arch Linux Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]> use student_info; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed MariaDB [student_info]> select *from stu_info;
+-------+---------+--------+-----------+------------------+----------+--------+---------+ | stuId | stuName | gender | phone | email | account | code | adminId | +-------+---------+--------+-----------+------------------+----------+--------+---------+ | 101 | 张三 | 女 | 423019223 | zhangsan@163.com | zhangsan | 110066 | 901 | +-------+---------+--------+-----------+------------------+----------+--------+---------+ 3 rows in set (0.001 sec)
人就像是被蒙着眼推磨的驴子,生活就像一条鞭子;当鞭子抽到你背上时,你就只能一直往前走,虽然连你也不知道要走到什么时候为止,便一直这么坚持着。