What is the proper way to create a local-database file and then connect the app to it ? I want it to work even if you change the location of the project folder.
Right know what I do is: Project -> Add new item -> Service-based Database and I create one and then I go to Data -> Add new Data Source, I add the created database and I get the connection string.
Ok, all good, I can connect to it as I wish BUT all my data is erased from the database when I close the application (not always).
For example, this code:
SqlConnection c = new SqlConnection(@"DataSource=.SQLEXPRESS;AttachDbFilename=|DataDirectory|DB.mdf;Integrated Security=True;User Instance=True");
c.Open();
SqlCommand cmd;
cmd = new SqlCommand("CREATE TABLE Persons (id int primary key, nume char(20), age int)");
cmd.ExecuteNonQuery();
cmd = new SqlCommand("INSERT INTO Persons VALUES (@id, @name, @age)", c);
cmd.Parameters.AddWithValue("@id", 1);
cmd.Parameters.AddWithValue("@name", "Catalin");
cmd.Parameters.AddWithValue("@age", 20);
cmd.ExecuteNonQuery();
I run it first time to create the table and add an item to it and then, then if I run it the second time without the sqlcommand to create the table persons, it tells me that there is no Persons object, BUT if I run the second time the project with the same code, it tells me that there is already a Persons object...
I am using Visual C# Express Edition 2010.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…