[SOLVED]
The problem stands in the relative path. I should've used the mdf located in the project folder rather than the one in bin
I try to insert some data into a database through a Windows forms program. The problem is that if I use a relative path in the connection string, the data stays in the table only while the program is running. Otherwise, with an absolute path in the connection string, it works well, but I really need to use a relative path.
Here I set the relative path in the form's constructor.
public Form1()
{
InitializeComponent();
string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
string path = (System.IO.Path.GetDirectoryName(executable));
AppDomain.CurrentDomain.SetData("DataDirectory", path);
update();
}
App.config:
<connectionStrings>
<add name="musicConnString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\music.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Finally, here I do the insert:
string connectionString = ConfigurationManager.ConnectionStrings["musicConnString"].ConnectionString;
using (SqlConnection sq = new SqlConnection(connectionString))
using (SqlCommand sc = new SqlCommand("INSERT INTO music VALUES(@artist, @album, @songs, @genre, @cover, @year)", sq))
{
sq.Open();
sc.Parameters.AddWithValue("@artist", artistTxt.Text.Trim());
sc.Parameters.AddWithValue("@album" , albumTxt.Text.Trim());
sc.Parameters.AddWithValue("@songs" , songsTxt.Text.Trim());
sc.Parameters.AddWithValue("@genre" , genreTxt.Text.Trim());
sc.Parameters.AddWithValue("@year" , yearTxt.Text.Trim());
sc.Parameters.AddWithValue("@cover" , imageToByte(albumCover));
if (sc.ExecuteNonQuery() > 0)
{
this.Dispose();
}
else
{
MessageBox.Show("There was a problem with the insertion.");
}
}