Content

SQLite3的绑定函数族使用与其注意事项详解

文章摘要

这篇文章介绍了在SQLite中使用C语言批量插入数据的操作过程。代码首先定义了一个SQLite语句对象,并准备了一个插入语句,随后使用`sqlite3_prepare_v2`函数绑定插入参数。文章详细描述了如何在循环中读取对话框中的文本输入,并根据不同字段的类型(如日期和数字)进行处理。例如,对于日期字段,代码将文本转换为日期格式并绑定;对于数字字段,则使用`sscanf_s`函数提取数值并绑定到数据库。文章还提到代码包括了错误处理逻辑,包括绑定失败和插入失败的情况。整体内容展现了如何高效地在SQLite中批量处理和插入数据。

 sqlite3_stmt *stmt; CString sql=”insert into work values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)”; int rc=sqlite3_prepare_v2(db, sql.GetString(), -1, &stmt, NULL); if(rc !=SQLITE_OK) { MessageBox(“sqlite3_prepare_v2 Failed!”); return; } count=0; p_wnd=PrevWnd; CString DbStr[ID_TOTALCOUNT + 1]; while(count++ < ID_TOTALCOUNT) { DbStr[count].Empty(); p_wnd=CWnd::GetNextDlgTabItem(p_wnd, FALSE); if(p_wnd==NULL) { return; } p_wnd->GetWindowText(DbStr[count]); do { if(!DbStr[count].GetLength()) { rc=sqlite3_bind_null(stmt, count); break; } //日期相关 if( count==ID_CHUDANRIQI || count==ID_CHUFARIQI || count==ID_HUANKUANRIQI || count==ID_HUOLIRIQI) { CDateTimeCtrl *TimeCtl=(CDateTimeCtrl *)p_wnd; CString time=DateTimeToString(*TimeCtl); DbStr[count]=time; rc=sqlite3_bind_text(stmt, count, time.GetString(), time.GetLength(), SQLITE_STATIC); } else { //金钱相关的处理real类型 if( count==ID_BAOXIANJINE || count==ID_YONGJINBILV || count==ID_JINGBAOFEI || count==ID_HUANKUANJINE || count==ID_LIRUNBILV || count==ID_LIRUNJINE) { double tMoney=0.0; int rtn=sscanf_s(DbStr[count].GetString(), “%lf”, &tMoney); ASSERT(rtn==1); rc=sqlite3_bind_double(stmt, count, tMoney); } else { rc=sqlite3_bind_text(stmt, count, DbStr[count].GetString(), DbStr[count].GetLength(), SQLITE_STATIC); } } }while(0); if(rc !=SQLITE_OK) { CString ErrStr=sqlite3_errstr(rc); MessageBox(ErrStr); return; } } rc=sqlite3_step(stmt); if(rc !=SQLITE_DONE) { if(rc==SQLITE_ERROR) { CString DbErr; DbErr.Format(“Sql Insert failed, %s”, sqlite3_errmsg(db)); MessageBox(DbErr); } else { MessageBox(“sqlite3_step Failed!”); } } sqlite3_finalize(stmt);