C# ADO.NET编程表示发生错误-ExecuteOnQuery需要打开且可用的连接
现在,我的教授要求我使用ADO.NET实现一个案例研究,将数据保存到SQL Server中。我已经在SQLServer中创建了一个数据库和表,并且正在尝试使用C#ADO.NET在Visual Studio中创建一些表单。我根据YouTube视频写作。但我不知道为什么我不能成功地将数据保存到数据库中 我这样写代码的结果 任何帮助都将不胜感激C# ADO.NET编程表示发生错误-ExecuteOnQuery需要打开且可用的连接,c#,sql-server,ado.net,C#,Sql Server,Ado.net,现在,我的教授要求我使用ADO.NET实现一个案例研究,将数据保存到SQL Server中。我已经在SQLServer中创建了一个数据库和表,并且正在尝试使用C#ADO.NET在Visual Studio中创建一些表单。我根据YouTube视频写作。但我不知道为什么我不能成功地将数据保存到数据库中 我这样写代码的结果 任何帮助都将不胜感激 namespace casestudy { public partial class Form2 : Form { SqlCo
namespace casestudy
{
public partial class Form2 : Form
{
SqlConnection vcon2 = new SqlConnection(@"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
vcon2.Open();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
{
string vsql = string.Format("insert into Calluser values ({0}, '{1}', '{2}', {3})", Int32.Parse(txtUserID.Text), txtFName.Text, txtLName.Text, Int32.Parse(txtZoneID.Text));
SqlCommand vCom = new SqlCommand(vsql, vcon2);
try
{
vCom.ExecuteNonQuery();
vCom.Dispose();
MessageBox.Show("The User Information stored.");
txtZoneID.Text = "";
txtLName.Text = "";
txtFName.Text = "";
txtUserID.Text = "";
txtUserID.Focus();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
}
}
在调用
ExecuteNonQuery()
当应用程序或表单打开时打开连接可能不是最好的方法。您希望在执行sql之前立即打开连接,并尽快将其关闭 也就是说,我建议从Form2_加载事件中删除代码。然后在按钮1中执行所有操作,单击或从那里调用其他方法。更好的做法是有一个类或组件为您的应用程序进行数据访问。还要使用using语句,因为它将确保即使引发异常也会释放资源
using (SqlConnection connection = new SqlConnection(@"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");))
{
SqlCommand command = new SqlCommand(vsql, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
有关using语句的一些信息:
您可以查看ExecuteOnQuery的结果。看看这是不是说可以。尝试将要存储值的列名添加到select语句1中。尽量遵循“迟开早关”的原则。也就是说,在click事件处理程序中打开和关闭连接。2.通常情况下,一个物体自行处理是不好的。对象的“创建者”负责处理。在您的示例中,如果单击处理程序中出现错误-表单自行处理,然后用户再次单击按钮,会发生什么情况?3.查阅一些关于“SQL注入”的文章。如果您的用户键入“');go;drop table CallUser;”的某个变体,该怎么办?代码看起来正常,您收到了什么错误消息?
using (SqlConnection connection = new SqlConnection(@"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");))
{
SqlCommand command = new SqlCommand(vsql, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}