How can I insert record in Microsoft Access?
CString SqlString; CString name="I want to add this variable in Table3"; SqlString = "INSERT INTO Table3 (Name,Numbers) VALUES (name,099)";
When I do it that way gives the following error:
Database error:Too few parameters.Expected 1.
CodePudding user response:
This is a snippet from my own application:
BOOL CCommunityTalksApp::SetRecordForTalkNumber(int iTalkNumber, UINT uID, CString &rStrError)
{
CDatabase *pDatabase;
CString strSQL, strField;
BOOL bOK;
pDatabase = theApp.GetDatabase();
if(pDatabase != nullptr)
{
if (iTalkNumber == 9999)
strField = _T(" ");
else
strField.LoadString(uID);
strSQL.Format(_T("INSERT INTO [Public Talk Titles] ([Theme], [Category], [Talk Number]) VALUES ('%s', 'NS', %d)"), strField, iTalkNumber);
TRY
{
pDatabase->ExecuteSQL((LPCTSTR)strSQL);
bOK = TRUE;
}
CATCH(CDBException, Except)
{
rStrError = Except->m_strError;
bOK = FALSE;
}
END_CATCH
}
return bOK;
}
As you can see:
- Use
[
and]
to wrap the table and field names to address any issues with spaces. - Qualify the field names first — particularly if you are only populating certain field values.
- Wrap the string values with single quotes.
So:
SqlString = "INSERT INTO Table3 (Name,Numbers) VALUES (name,099)";
Would be something like:
SqlString = "INSERT INTO [Table3] ([Name],[Numbers]) VALUES ('name',099)";
I appreciate that the square brackets are not needed for your table / field names though.