Reputation: 133
So, I'm trying to insert data into a table using SQLite in C. The insert works fine whenever I do it without specifying the columns I'm going to insert the data to. However, I want to use the primary key property in one of my columns, so I tried using the INSERT INTO table name (columns) VALUES (values) method and it's not working.
Table creation:
snprintf(sql_query,sizeof(sql_query), "CREATE TABLE IF NOT EXISTS %s(%s INTEGER PRIMARY KEY,%s TEXT NOT NULL, %s TEXT NOT NULL, %s TEXT NOT NULL,%s REAL NOT NULL, %s REAL NOT NULL, %s REAL NOT NULL);",tbl_id1,tbl_col1,tbl_col2,tbl_col3,tbl_col4,tbl_col5,tbl_col6,tbl_col7);
rc = sqlite3_exec(db, sql_query, callback, 0, NULL);
Insert:
sprintf(sql, "INSERT INTO %s (%s,%s,%s,%s,%s,%s) VALUES ('%d/%d/%d','%d:%d:%d','4','%d','%d','7');",tbl_id1,tbl_col2,tbl_col3,tbl_col4,tbl_col5,tbl_col6,tbl_col7,year,month,day,hour,min,sec,peak,real);
int ic = sqlite3_exec(db, sql, callback, 0, NULL);
As I said, it works fine if I were to do it without specifying the columns I want to insert the data into.
Edit: Names of my variables
#define db_name "db_test.db"
#define tbl_id1 "Meter1"
#define tbl_id2 "Meter2"
#define tbl_id3 "Meter3"
#define tbl_col1 "Run[#]"
#define tbl_col2 "Date[YY-MM-DD]"
#define tbl_col3 "Time[HH:MM:SS]"
#define tbl_col4 "Accept[True/False]"
#define tbl_col5 "F_Peak[N/cm]"
#define tbl_col6 "m_Peak[g]"
#define tbl_col7 "Cycle[s]"
Upvotes: 0
Views: 292
Reputation: 3690
The issue is in the column names. With given values, sqlite3_exec returns SQLITE_ERROR (1) instead of SQLITE_OK (0).
Use column names without brackets (and everything within them) in INSERT query. For your example use following column names:
#define tbl_col1_clear "Run"
#define tbl_col2_clear "Date"
#define tbl_col3_clear "Time"
#define tbl_col4_clear "Accept"
#define tbl_col5_clear "F_Peak"
#define tbl_col6_clear "m_Peak"
#define tbl_col7_clear "Cycle"
Upvotes: 1