我正在尝试将用户在Winform上输入的值插入到以下Access表中:
C#代码是:
OleDbCommand oleCmd = new OleDbCommand("INSERT INTO Projects (projectTitle,partyID,receiveDate,dueDate, projectTypeID, pages, "+
"lines, words, prepay, cost, settled,projectComment)"
+ " VALUES (@projectTitle,@partyID,@receiveDate,@dueDate,@projectTypeID,@pages, @lines, @words, @prepay, @cost, @settled, @projectComment)", conn);
PersianCalendar p=new PersianCalendar();
DateTime thisDate=DateTime.Now;
oleCmd.Parameters.Add("@projectTitle", OleDbType.VarChar).Value = txtProjectTitle.Text;
oleCmd.Parameters.Add("@partyID", OleDbType.Numeric).Value = Convert.ToInt32(comboProjectType.SelectedValue.ToString());
oleCmd.Parameters.AddWithValue("@receiveDate", string.Format( "{0}, {1}/{2}/{3} {4}:{5}:{6}",
p.GetDayOfWeek(thisDate), p.GetYear(thisDate),p.GetMonth(thisDate),p.GetDayOfMonth(thisDate), p.GetHour(thisDate),p.GetMinute(thisDate),p.GetSecond(thisDate))) ;
oleCmd.Parameters.Add("@dueDate", OleDbType.VarChar).Value = comboDay.Text + "/" + comboMonth.Text + "/" + comboYear.Text;
oleCmd.Parameters.Add("@projectTypeID", OleDbType.Numeric).Value = Convert.ToInt32(comboContractParty.SelectedValue.ToString());
oleCmd.Parameters.AddWithValue("@pages", Convert.ToInt32(txtPages.Text));
oleCmd.Parameters.AddWithValue("@lines", Convert.ToInt32(txtLines.Text));
oleCmd.Parameters.AddWithValue("@words", Convert.ToInt32(txtWords.Text));
oleCmd.Parameters.AddWithValue("@cost", Convert.ToDouble(txtWholeProjCost.Text));
oleCmd.Parameters.AddWithValue("@prepay", Convert.ToDouble(txtPrePay.Text));
oleCmd.Parameters.AddWithValue("@settled", chkSettled.CheckState);
oleCmd.Parameters.Add("@projectComment", OleDbType.VarChar).Value = txtComment.Text.ToString();
try
{
conn.Open();
oleCmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
例外说:
标准表达式中的数据类型不匹配。
我重新检查了类型,但不知道错误的来源。
答案 0 :(得分:1)
receiveDate
和dueDate
在数据库中定义为DateTime
,但您将文本(字符串)传递给参数:
oleCmd.Parameters.AddWithValue("@receiveDate", string.Format(...
oleCmd.Parameters.Add("@dueDate", OleDbType.VarChar).Value = ...
传递实际的DateTime
vars,它应该有效。由于日期是碎片,我会先创建它们,以便进行测试:
// why not use thisDate rather than chopping it up to recombine?
DateTime recDate = New DateTime(p.Getyear(thisDate)...);
// personally, I might use a DateTimePicker rather than 3 CBOs
DateTime dueDate = New DateTime(ConvertToInt32(comboYear.Text), ...
然后将它们作为参数传递给他们。如果您使用Add
指定OleDbType.Date
:
oleCmd.Parameters.AddWithValue("@receiveDate", recDate);
...
oleCmd.Parameters.AddWithValue("@dueDate", dueDate);