从C#应用程序表单传递值到数据库

时间:2009-12-18 19:35:00

标签: c# insert sql

尝试将从文本框接收的几个值插入到Access数据库的表中。 我已经完美地编写了我的语句而没有为表中的主键传递值,因为它的数据类型设置为自动编号。

运行程序。我单击运行插入语句的按钮,我收到以下错误“查询值和目的地字段数不相同”

我该如何解决这个问题??

如果需要进一步的信息,请告诉我.... 感谢...

2 个答案:

答案 0 :(得分:2)

您是否列出了要插入的列?

INSERT INTO table (col1, col2) VALUES (val1, val2)

如果你没有插入每一列,你必须这样做,并且无论如何都应该这样做,因为这是最好的做法。

答案 1 :(得分:2)

您应该使用这样的问题发布您的查询,但我想我知道您的问题是什么。

由于您没有使用主键列,因此只插入字段的子集,您需要列出您将使用的字段,如下所示:

INSERT INTO SomeTable (col1,col2,col3) VALUES ('val1','val2',3)

你可能试图做这样的事情:

INSERT INTO SomeTable VALUES ('val1','val2',3)

这不起作用,因为您的主键字段是自动编号的。

试试这个:

sqlQuery = 
"INSERT INTO Youth (" + 
"NumbersOfSport, " + 
"YouthID, " + 
"Price, " + 
"TotalCostOfTraining, " + 
"PercentageDiscount, " + 
"AmountDue," + 
"DatePurchased" + 
") VALUES (" + 
toSql(qtyInt) + ", " + 
toSql(youthInt) + ", " + 
toSql(priceStr) + ", " + 
toSql(totalCstStr) + ", " + 
toSql(discountStr) + ", " + 
toSql(amtDueStr) + ", " + 
toSql(Convert.ToDateTime(purDate)) + ")"

你在这里错过了一个逗号:“AmountDue”+ 应该是:“AmountDue”,+

VB格式:

sqlQuery =“INSERT INTO Youth(”+“NumbersOfSport,”+“YouthID,”+“Price,”+“TotalCostOfTraining,”+“PercentageDiscount,”+“AmountDue”+“DatePurchased”+“)VALUES(” + toSql(qtyInt)+“,”+ toSql(youthInt)+“,”+ toSql(priceStr)+“,”+ toSql(totalCstStr)+“,”+ toSql(discountStr)+“,”+ toSql(amtDueStr) +“,”+ toSql(Convert.ToDateTime(purDate))+“)”