关闭后数据库连接错误然后再次打开数据源

database connection error after close then open again the data source

我在连接到数据库时出现异常,我在 Login.cs 文件中打开连接然后在此处关闭它,然后在 Select_Item.cs 处打开连接,但是我仍然得到错误说:

A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

我在 Select_Item.cs 文件的第 "con.Open();"

行收到错误

Login.cs:

private void button2_Click(object sender, EventArgs e)
    {


        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\xchoo\Documents\Visual Studio 2012\Projects\WindowsFormsApplication_test2\WindowsFormsApplication_test2\Data.mdf;Integrated Security=True;Connect Timeout=30");
        //con.Close();
        SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From custInfo where Username='" + USERNAME.Text + "'and Password='" + PASSWORD.Text + "'", con);
        DataTable custInfo=new DataTable();
        //con.Close();
        sda.Fill(custInfo);


        if (custInfo.Rows[0][0].ToString() == "1")
        {
        this.Hide();
        Select_Item select_item = new Select_Item();
        select_item.Show();
        con.Close();
        }
        else
        {
        MessageBox.Show("Please check your Username and Password");
        }
    }

Select_Item.cs

private void StoreData()
    {
        int invoiceID;


        using (var con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\choo\Documents\Visual Studio 2012\Projects\WindowsFormsApplication_test2\WindowsFormsApplication_test2\Data.mdf;Integrated Security=True;Connect Timeout=30"))
        //using (con)
        {

            con.Open();
            //Invoice.Columns.Add(invoiceID);
           // invoiceID.AutoIncrement = true;
            using (var cmd = con.CreateCommand())
            {
                cmd.CommandText = @"insert into Invoice(invoiceID, subtotal,tax,total) values (1, @subtotal,@tax,@total); select SCOPE_IDENTITY() as InvoiceID;";
                cmd.Parameters.AddWithValue("@subtotal", subtotal);
                cmd.Parameters.AddWithValue("@tax", tax);
                cmd.Parameters.AddWithValue("@total", total);
                using (var reader = cmd.ExecuteReader())
                {
                    if (reader.Read())

                        invoiceID = (int)reader["InvoiceID"];

                }
            }
            foreach (var item in OrderItems.Rows)
            {
                using (var cmd = con.CreateCommand())
                {

                    cmd.CommandText = @"insert into InvoiceItem(invoiceID,Item_Id,quantity) values (@invoiceID,@Item_Id,@quantity);";
                   // cmd.Parameters.AddWithValue("@InvoiceID", invoiceID);
                    cmd.Parameters.AddWithValue("@invoiceID", Convert.ToInt32("invoiceID"));
                    cmd.Parameters.AddWithValue("@Item_Id", Convert.ToInt32("Item_Id"));
                    cmd.Parameters.AddWithValue("@quantity", Convert.ToInt32("quantity"));
                    cmd.ExecuteNonQuery();



                }
            }
        }
    }

App.config:

    <?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="WindowsFormsApplication_test2.Properties.Settings.Database1ConnectionString"

             connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\xchoo\Documents\Visual Studio 2012\Projects\WindowsFormsApplication_test2\WindowsFormsApplication_test2\Data.mdf;Integrated Security=True;Connect Timeout=30"

            providerName="Microsoft.SqlServerCe.Client.4.0" />
        <add name="WindowsFormsApplication_test2.Properties.Settings.DataConnectionString"


               connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\xchoo\Documents\Visual Studio 2012\Projects\WindowsFormsApplication_test2\WindowsFormsApplication_test2\Data.mdf;Integrated Security=True;Connect Timeout=30"

             providerName="System.Data.SqlClient" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

我有两个建议给你:

1:连接时请使用using中的Login.cs语句。请在下面找到代码。

private void button2_Click(object sender, EventArgs e)
{
    using(SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\xchoo\Documents\Visual Studio 2012\Projects\WindowsFormsApplication_test2\WindowsFormsApplication_test2\Data.mdf;Integrated Security=True;Connect Timeout=30"))
    //con.Close();
  {
    SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From custInfo where Username='" + USERNAME.Text + "'and Password='" + PASSWORD.Text + "'", con);
    DataTable custInfo=new DataTable();
    //con.Close();
    sda.Fill(custInfo);


    if (custInfo.Rows[0][0].ToString() == "1")
    {
    this.Hide();
    Select_Item select_item = new Select_Item();
    select_item.Show();
    con.Close();
    }
    else
    {
    MessageBox.Show("Please check your Username and Password");
    }
  }
}

2nd : 请将连接字符串保留在 App.Config 或 Web.Config 中并尝试从那里访问它。