[英]When inputting data into my T-SQL table from C#, I get an error
I am creating a register like program using C# and a local SQL Server database. 我正在使用C#和本地SQL Server数据库创建类似程序的寄存器。
I have managed to create a query that inputs the data into the table called UserAdd
. 我设法创建了一个查询,该查询将数据输入到名为
UserAdd
的表中。
Code: 码:
ALTER PROCEDURE UserAdd
@Name VARCHAR(30),
@Organisation VARCHAR(20),
@DOB DATETIME,
@Contact VARCHAR(50),
@Address VARCHAR(250)
AS
INSERT INTO Member(Name, Organisation, DOB, Contact, Address)
VALUES (@Name, @Organisation, @DOB, @Contact, @Address)
After creating this I used the code below to ensure it was passed through the query and added to the database: 创建此代码后,我使用下面的代码来确保它通过查询传递并添加到数据库中:
private void Btn_Submit_Click(object sender, EventArgs e)
{
if (Txt_NameReg.Text == "")
{
MessageBox.Show("Please fill required fields(*)");
}
else
{
using (SqlConnection SQLCon = new SqlConnection(ConnectionString))
{
SQLCon.Open();
SqlCommand SqlCmd = new SqlCommand("UserAdd", SQLCon);
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCmd.Parameters.AddWithValue("@Name", Txt_NameReg.Text.Trim());
SqlCmd.Parameters.AddWithValue("@Organisation", Txt_OrgReg.Text.Trim());
SqlCmd.Parameters.AddWithValue("@DOB", DT_DobReg.Value.ToString("dd-MM-yyyy"));
SqlCmd.Parameters.AddWithValue("@Contact", Txt_RegCont.Text.Trim());
SqlCmd.Parameters.AddWithValue("@Address",Txt_RegAddress.Text.Trim());
SqlCmd.ExecuteNonQuery();
MessageBox.Show("Registration Successfull");
Clear();
}
}
}
void Clear()
{
Txt_NameReg.Text = Txt_OrgReg.Text = DT_DobReg.Text = Txt_RegCont.Text = Txt_RegAddress.Text = "";
}
During the testing of this I receive the expected message of "Registration successful" 在测试过程中,我收到了“注册成功”的预期消息
However when I look at the database values, they are empty and I receive this error: 但是,当我查看数据库值时,它们为空,并且收到此错误:
How can I ensure the data is input into the table? 如何确保将数据输入到表中?
EDIT: Connection string: 编辑:连接字符串:
string ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\GardenRegister.mdf;Integrated Security=True";
Try Closing your connection with SQLCon.Close();
尝试使用
SQLCon.Close();
关闭连接SQLCon.Close();
at the end of your using statement. 在using语句的末尾。
Also move SQLCon.Open();
还移动
SQLCon.Open();
to the line before you execute the query (Although that is nothing to do with your issue but best practice) 在执行查询之前移至该行(尽管与您的问题无关,但最佳实践)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.