Working on a WinForm project making use of SQL Server.
Currently my MusicPlayerDB.mdf
has its Copy to Output Directory
property set to Copy if newer
.
After I run my InsertIntoDB
, I close the Winform and proceed to check the table over in Server Explorer. But is seems as my table wasn't updated. But if I go to check Bin/Debug
and check MusicPlayerDB.mdf
, the data is there.
What would be the best way to fix this? I've seen other comments saying to use the absolute path of the .mdf
(or something along those lines), but I would like to avoid that if possible.
Here is my connection string,
private const String CONNECTION_STRING = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MusicPlayerDB.mdf;Integrated Security=True";
And here is my insert code:
private static void InsertIntoDB(List<string> userAccout)
{
String sqlQuery = "INSERT INTO dbo.UserAccount (UserName, UserPassword, PasswordQuestion, PasswordHint, PasswordKey) "
+ "VALUES (@UserName, @UserPassword, @PasswordQuestion, @PasswordHint, @PasswordKey);";
using(SqlConnection connection = new SqlConnection(CONNECTION_STRING))
{
connection.Open(); //open connection
using(SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// set up command
using(SqlTransaction trans = connection.BeginTransaction())
{
try
{
command.Connection = connection;
command.Transaction = trans;
command.Parameters.AddWithValue("@UserName", userAccout[0]);
command.Parameters.AddWithValue("@UserPassword", userAccout[1]);
command.Parameters.AddWithValue("@PasswordQuestion", userAccout[2]);
command.Parameters.AddWithValue("@PasswordHint", userAccout[3]);
command.Parameters.AddWithValue("@PasswordKey", Convert.ToInt32(userAccout[4]));
int r = command.ExecuteNonQuery(); //execute the command
trans.Commit();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message); //couldn't execute command
}
}
}
}
} //end of InsertIntoDB