我試圖從C#Winforms插入到SQL Server數據庫的costumer的信息,雖然當我點擊添加按鈕時沒有錯誤顯示,沒有數據正在被添加到數據庫中。INSERT語句不插入SQL Server數據庫使用C#Winform
下面是添加函數的代碼:
private void acceptButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
String query = "INSERT INTO Costumer(Name, Address, Phone, Note) VALUES(@name, @address, @phone, @note)";
SqlCommand command = new SqlCommand(query, con);
command.Parameters.AddWithValue("@name", nameTextBox.Text);
command.Parameters.AddWithValue("@address", addressTextBox.Text);
command.Parameters.AddWithValue("@phone", phoneTextBox.Text);
command.Parameters.AddWithValue("@note", noteTextBox.Text);
try
{
con.Open();
command.ExecuteNonQuery();
con.Close();
this.Close();
}
catch (SqlException exception)
{
MessageBox.Show(exception.Message.ToString(), "Error Message");
}
}
這裏是負荷消費表
CREATE TABLE [dbo].[Costumer] (
[CostumerId] INT IDENTITY (1, 1) NOT NULL,
[Name] VARCHAR (50) NULL,
[Address] VARCHAR (50) NULL,
[Phone] VARCHAR (16) NULL,
[Note] VARCHAR (250) NULL,
PRIMARY KEY CLUSTERED ([CostumerId] ASC)
);
不知道在哪裏的問題是這裏的設計。
編輯:我在winform項目中使用的連接字符串。
這裏是連接字符串:
<add name="myConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\database.mdf;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient"/>
我已經使用了相同的連接字符串幾個SELECT查詢和他們工作得很好。
能否請您*我們展示*連接字符串你在用嗎? –
'command.ExecuteNonQuery'返回成功執行的行數。如果它不止一個,那麼你可能正在查看錯誤的數據庫。 – LarsTech
用連接字符串編輯問題。 – Alfasatwi