ADO.NET programming says error occured - ExecuteNonQuery requires an open and available connection

亡梦爱人 提交于 2019-12-25 01:19:06

问题


Right now, my professor requires me to implement a case study using ADO.NET to save data into SQL Server. I have already created a database and tables in SQL Server and I'm trying to create some forms in Visual Studio by C# ADO.NET. I write according to a YouTube video. But I don't know why I cannot save my data to database successfully.

The result as I write my code like this.

Any help would be appreciated.

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();
        }
    }
}
}

回答1:


Can you add a check to see if the connection is actually open and if not reopen it just before you call the ExecuteNonQuery()

if (vcon2.State != ConnectionState.Open)
{
    vcon2.Open();
}
vCom.ExecuteNonQuery();



回答2:


Opening the connection when the application or form opens is probably not the best approach. You want to open the connection right before you execute your sql and close it as soon as possible.

That being said, I recommend removing the code from the Form2_Load event. And do everything in the button1_Click or another method you call from there. Even better would be to have a class or component that does the data access for your application. Also use a using statement as it will ensure resources are disposed even if an exception is thrown.

    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();
    }

Some info on the using statement:

http://www.dotnetperls.com/using

https://msdn.microsoft.com/en-us/library/yh598w02.aspx



来源:https://stackoverflow.com/questions/36519879/ado-net-programming-says-error-occured-executenonquery-requires-an-open-and-av

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!