我正在为数据库使用Access。表乘客具有以下 我似乎找不到问题所在。有人可以帮帮我吗
Passenger Number(Auto Number)
FirstName (short text)
LastName (short text)
Initials (short text)
ID_number (short text)
Gender (short text)
Date_of_Birth (Date/Time)
Cell_Number (short text)
Street_Number (number)
Street_Name (short text)
Postal_Code (number)
//这些是我的变量
string name = txtFirstName.Text;
string surname = textBox3.Text;
string initials = textBox2.Text;
string id = textBox6.Text;
string gender = comboBox1.SelectedItem.ToString();
string dest = cmbDestination.SelectedValue.ToString();
string num =textBox9.Text;
string snum = textBox8.Text;
string sname = textBox7.Text;
string pcode = comboBox2.SelectedItem.ToString();
string date = dateTimePicker1.Text;
//这是我的代码,应该向表乘客添加新记录,但我不断收到错误消息
try
{
using (OleDbConnection connect = new
OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=" + Application.StartupPath + "\\Database3.accdb"))
{
OleDbCommand cmd = new OleDbCommand("INSERT INTO
Passengers ([FirstName],[LastName],[Initials] ,
[ID_number],[Gender],[Date_Of_Birth],[Cell_Number],
[Street_Number], [Street_Name],[Postal_Code]) VALUES
(?,?,?,?,?,?,?,?,?,?)", connect);
cmd.Connection = connect;
cmd.Parameters.AddWithValue("@FirstName", name);
cmd.Parameters.AddWithValue("@LastName", surname);
cmd.Parameters.AddWithValue("@Initials", initials);
cmd.Parameters.AddWithValue("@ID_number", id);
cmd.Parameters.AddWithValue("@Gender", gender);
cmd.Parameters.AddWithValue("@Date_Of_Birth", date);
cmd.Parameters.AddWithValue("@Cell_Number", num);
cmd.Parameters.AddWithValue("@Street_Number", snum);
cmd.Parameters.AddWithValue("@Street_Name", sname);
cmd.Parameters.AddWithValue("@Postal_Code", pcode);
connect.Open();
cmd.ExecuteNonQuery();
OleDbDataAdapter adapt = new OleDbDataAdapter("SELECT *
FROM Passengers", connect);
MessageBox.Show("Seat successfully booked for
passenger!");
Console.Beep(659, 125); Console.Beep(659, 125);
Console.Beep(659, 125);
this.Close();
connect.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
答案 0 :(得分:2)
示例代码中存在多个列值分配问题,在这种情况下,您要将string
值传递给类型为number
或date
的列,这会导致数据类型不匹配例外。
您应该使用AddWithValue
来指定适当的数据类型和值,而不是像所有示例那样使用OleDbCommand.Parameters.Add()
:
// note: use DateTime.ParseExact for specific date formatting
cmd.Parameters.Add("@Date_Of_Birth", OleDbType.Date).Value = DateTime.Parse(dateTimePicker1.Text);
cmd.Parameters.Add("@Street_Number", OleDbType.Integer).Value = int.Parse(textBox8.Text);
cmd.Parameters.Add("@Postal_Code", OleDbType.Integer).Value = int.Parse(comboBox2.SelectedItem.ToString());
编辑:
对于DateTimePicker
控件,您可以使用DateTime
类型的Value
属性:
cmd.Parameters.Add("@Date_Of_Birth", OleDbType.Date).Value = dateTimePicker1.Value;