如果文本框是空的,我已經設置了一個INSERT語句直到返回值到數據庫,但它仍然在插入時失敗。返回空值來通過OleDb訪問數據庫
我遇到'沒有給出一個或多個必需參數的值。'
我在哪裏出錯?
我在訪問字段沒有被設置所需
private void NewCustomer_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection Conn = new OleDbConnection();
Conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BoilerSvc_be.mdb";
OleDbCommand command = new OleDbCommand();
command.CommandText = "INSERT INTO Contacts (Title,Initial,Surname,[Address 1],[Address 2],[Address 3],[Post Town],[Post Code],Telephone,Archived) VALUES (@Title,@FirstName,@LastName,@Address1,@Address2,@Address3,@PostTown,@PostCode,@Telephone,Archived = 0)";
if (string.IsNullOrEmpty(FirstName.Text))
{
command.Parameters.AddWithValue("@FirstName", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("@FirstName", title.Text);
}
if (string.IsNullOrEmpty(LastName.Text))
{
command.Parameters.AddWithValue("@LastName", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("@LastName", title.Text);
}
if (string.IsNullOrEmpty(Address1.Text))
{
command.Parameters.AddWithValue("@Address1", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("@Address1", title.Text);
}
if (string.IsNullOrEmpty(Address2.Text))
{
command.Parameters.AddWithValue("@Address2", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("@Address2", title.Text);
}
if (string.IsNullOrEmpty(Address3.Text))
{
command.Parameters.AddWithValue("@Address3", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("@Address3", title.Text);
}
if (string.IsNullOrEmpty(Postcode.Text))
{
command.Parameters.AddWithValue("@PostCode", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("@PostCode", title.Text);
}
if (string.IsNullOrEmpty(TownCity.Text))
{
command.Parameters.AddWithValue("@PostTown", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("@PostTown", title.Text);
}
if (string.IsNullOrEmpty(PhnNum.Text))
{
command.Parameters.AddWithValue("@Telephone", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("@Telephone", title.Text);
}
if (string.IsNullOrEmpty(Titl.Text))
{
command.Parameters.AddWithValue("@Title", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("@Title", title.Text);
}
Conn.Open();
command.Connection = Conn;
command.ExecuteNonQuery();
Conn.Close();
FirstName.Text = null;
LastName.Text = null;
Address1.Text = null;
Address2.Text = null;
Address2.Text = null;
Postcode.Text = null;
TownCity.Text = null;
Titl.Text = null;
PhnNum.Text = null;
Address3.Text = null;
MessageBox.Show("Customer Added");
}
我想你應該在最後刪除「存檔= 0」。並且把0換成 – Danieboy
除了別的之外,我不認爲'OleDbCommand'根本不支持命名參數:「OLE DB .NET Provider不支持將參數傳遞給SQL語句或者存儲過程的命名參數當CommandType設置爲Text時,一個OleDbCommand。在這種情況下,必須使用問號(?)佔位符。「 –
1.你在'AddWithValue'的任何地方都有'title.Text',你的意思是添加該項目的特定文本。 2.'Archived = 0'不會工作,因爲在插入時你不知道'Archived'的值,你需要提供一個值(這是主要的罪魁禍首)。 3.將你的Connection對象封裝在'using'語句中,以便它始終關閉。 4.參數很好,但請不要忘記指定參數類型,您可以將其鏈接到「AddWithValue」。最後,參數是基於OleDb的位置,因此查詢中參數的順序應與收集中的參數完全匹配。 – Igor