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

随心笔谈2年前发布 admin
173 0 0

文章摘要

这篇文章描述了一段C++代码,用于将一组数据插入到SQLite数据库中。代码首先初始化了一个SQLite语句句柄,并准备了一个插入语句。然后,代码通过循环处理每个字段,根据字段类型(如日期、金额等)分别进行处理: 1. 对于日期字段,使用CDateTimeCtrl获取时间字符串并绑定到数据库。 2. 对于金额字段,使用sscanf_s函数将字符串转换为double类型并绑定到数据库。 3. 对于其他字段,直接将字符串绑定到数据库。 代码还包含错误处理逻辑,包括检查 prepared 语句的返回值,处理绑定失败和绑定成功后的执行结果。最后,代码执行了插入操作,并进行了数据库句柄的释放。


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

© 版权声明

相关文章