0

My connection string used to be like this:

SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=G:\I.S\C#\billingSystem\Store.mdf;Integrated Security=True;User Instance=True");

so i can (insert, update, delete) with this:

    SqlCommand cmd = new SqlCommand("SQLSTATEMENT", cn);
    cn.Open();
    cmd.ExecuteNonQuery();
    cn.Close();

I've seen a tutorial on youtube called "Deploy C# Project", when he used

System.Configuration;

and the app.config file, so I followed the tutorial exact the same way and it works.

The problem that after I (insert, update, delete) at runtime everything is okay until I close the application it's like I've did nothing at all the data that I've inserted is gone!.

I need to save the changes into the table at runtime.

Some info: Winforms app, sample from my code:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="SchoolProjectConnectionString"
            connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\SchoolDB.mdf;Integrated Security=True;User Instance=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

namespace SchoolProject
{
    public partial class Main : Form
    {
        SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SchoolProjectConnectionString"].ToString());
        public Main()
        {
            InitializeComponent();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string myValue = Interaction.InputBox("Enter ID", "ID", "", 100, 100);
            string myValue0 = Interaction.InputBox("Enter Name", "Name", "", 100, 100);
            int X = Convert.ToInt32(myValue);

            SqlCommand cmd = new SqlCommand("Insert into Student(ID, Student) Values ('" + X + "','" + myValue0 + "')", cn);
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string myValue3 = Interaction.InputBox("Enter ID", "ID", "", 100, 100);
            int X = Convert.ToInt32(myValue3);

            SqlCommand cmd = new SqlCommand("SELECT * FROM Student WHERE id = '" + X + "'", cn);
            cn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    MessageBox.Show(reader["Student"].ToString());
                }
            }
            cn.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Report R = new Report();
            R.Show();
        }
    }
}
4

1 回答 1

2

The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!

If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.

The real solution in my opinion would be to

  1. install SQL Server Express (and you've already done that anyway)

  2. install SQL Server Management Studio Express

  3. create your database in SSMS Express, give it a logical name (e.g. Store)

  4. connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:

    Data Source=.\\SQLEXPRESS;Database=Store;Integrated Security=True
    

    and everything else is exactly the same as before...

Also: you should read up on SQL injection and change your code to avoid that - it's the #1 security risk for apps. You should use parametrized queries in ADO.NET instead - those are safe, and they're faster, too!

于 2013-07-07T11:45:03.480 回答