1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
| #include<mysql.h>
| #include<iostream>
| #include<string>
| using namespace std;
|
| const char* host = "127.0.0.1";
| const char* user = "root";
| const char* pw = "123456";
| const char* database_name = "database_test";
| const int port = 3306;
|
| typedef struct Student
| {
| int student_id;
| string student_name;
| string class_id;
| }Student;
| int main()
| {
| MYSQL* con = mysql_init(NULL);
| //设置字符编码
| mysql_options(con, MYSQL_SET_CHARSET_NAME, "GBK");
|
| if (!mysql_real_connect(con, host, user, pw, database_name, port, NULL, 0))
| {
| fprintf(stderr, "Failed to connect to database : Error:%s\n", mysql_error(con));
| return -1;
| }
|
| Student stu{ 1111, "吴彦祖", "软件一班" };
|
| char sql[1024];
| //sprintf(sql, "insert into students (student_id,student_name,class_id) values(%d,'%s','%s')",
| // stu.student_id, stu.student_name.c_str(), stu.class_id.c_str());
| sprintf_s(sql, sizeof(sql), "insert into students (student_id,student_name,class_id) values(%d,'%s','%s')",
| stu.student_id, stu.student_name.c_str(), stu.class_id.c_str());
|
| if (mysql_query(con, sql))
| {
| fprintf(stderr, "Failed to insert data : Error:%s\n", mysql_error(con));
| return -1;
| }
|
| mysql_close(con);
| system("pause");
| return 0;
| }
|
|