在C中使用SQLite的INSERT INTO遇到麻烦

时间:2018-08-22 16:47:25

标签: c database sqlite

因此,我正在尝试使用C语言中的SQLite将数据插入表中。只要我不指定要插入数据的列,插入就可以正常工作。但是,我想在其中一列中使用主键属性,因此尝试使用INSERT INTO表名(列)VALUES(值)方法,但该方法不起作用。

表创建:

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);

插入:

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);

正如我所说,如果我不指定要插入数据的列就可以正常工作。

编辑: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]"

1 个答案:

答案 0 :(得分:1)

问题出在 列名 。对于给定的值,sqlite3_exec返回SQLITE_ERROR(1)而不是SQLITE_OK(0)。

在INSERT查询中使用不带括号的列名(及其中的所有内容)。对于您的示例,请使用以下列名称:

#<..... some XML .....>

<sec id="aj387295s3">
<label>3.</label>
<title><italic>CHANDRA</italic> OBSERVATIONS</title>
<p>The 13 candidates were observed with the Advanced CCD Imaging 
Spectrometer (ACIS; Burke et&nbsp;al. <xref ref-type="bibr" 
rid="aj387295r8">1997</xref>) on board <italic>Chandra</italic> 
(Weisskopf et&nbsp;al. <xref ref-type="bibr" 
rid="aj387295r46">1996</xref>). We chose the S3 chip to image the 
sources because of its better low-energy sensitivity. The standard 
TIMED readout with a frame time of 3.2 s was used, and the data were 
collected in VFAINT mode. In 12 cases, our <italic>Chandra</italic> 
observations led us to conclude that the RASS detection was not of a 
candidate INS (see Table&nbsp;<xref ref-type="table" 
rid="aj387295t1">1</xref>; the <xref ref-type="sec" 
rid="aj387295app1">Appendix</xref> includes a case-by-case discussion 
of these sources).</p>

#<..... more XML ....>