问题
I've followed this MySQL Manual to the letter, and changed it slightly to try and make a program that inserts 4 values into table. The structure of the table is:
MariaDB [(none)]> desc analytics.live;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| dat_sent | int(11) | NO | | NULL | |
| machine_id | varchar(33) | YES | | NULL | |
| foreign_addr | varchar(50) | YES | | NULL | |
| con_state | varchar(50) | YES | | NULL | |
| count | int(11) | NO | | NULL | |
+--------------+-------------+------+-----+---------+-------+
I have compiled it, and can successfully write to database.. However I'm struggling to understand how I'm going to pass arguments into the script.
My goal is to have it so that I can pass 4 arguments into the script, from the cli in the fashion:-
./a.out 0 "989b3gf047196h2243bd395a97cde4c" "192.168.0.1" "ESTABLISHED"
At the minute, the code base is here: https://pastebin.com/npP1C8uz
My question is, how would I make it so that it accepts each argv[] as part of the INSERT?
回答1:
I was using only one array for strings, needed to use one for each field (and the accompanying counts)
Got it working :)
Completed code-
https://pastebin.com/WS1Qx050
I had to bind each of the fields to their own data strings. To do this, I had to firstly define each field accordingly:
MYSQL *mysql = mysql_init(NULL);
MYSQL_STMT *stmt;
MYSQL_BIND bind[4];
int param_count;
// short small_data;
int f1_data;
char f2_data[STRING_SIZE];
char f3_data[STRING_SIZE];
char f4_data[STRING_SIZE];
unsigned long f2_length;
unsigned long f3_length;
unsigned long f4_length;
Then, before I got to the stage of INSERT, I declared the .buffer property for each bind as pointer to it's respective array.
/* Bind data for all 4 parameters */
memset(bind, 0, sizeof(bind));
/* INTEGER PARAM */
bind[0].buffer_type= MYSQL_TYPE_LONG;
bind[0].buffer= (char *)&f1_data;
bind[0].is_null= 0;
bind[0].length= 0;
/* STRING PARAM */
bind[1].buffer_type= MYSQL_TYPE_STRING;
bind[1].buffer= (char *)f2_data;
bind[1].buffer_length= STRING_SIZE;
bind[1].is_null= 0;
bind[1].length= &f2_length;
/* STRING PARAM */
bind[2].buffer_type= MYSQL_TYPE_STRING;
bind[2].buffer= (char *)f3_data;
bind[2].buffer_length= STRING_SIZE;
bind[2].is_null= 0;
bind[2].length= &f3_length;
/* STRING PARAM */
bind[3].buffer_type= MYSQL_TYPE_STRING;
bind[3].buffer= (char *)f4_data;
bind[3].buffer_length= STRING_SIZE;
bind[3].is_null= 0;
bind[3].length= &f4_length;
Doing this allowed me to properly commit the insert query to MySQL, filling in all the ?'s in the prepared statement defined at line 8.
来源:https://stackoverflow.com/questions/63139327/c-mysql-api-prepared-statements