繁体   English   中英

C# Winform SQL 服务器连接字符串

[英]C# Winform SQL Server Connection String

使用 SQL 服务器处理 WinForm 项目。

目前,我的MusicPlayerDB.mdf将其Copy to Output Directory属性设置为Copy if newer

运行InsertIntoDB后,我关闭 Winform 并继续在服务器资源管理器中检查表。 但似乎我的表没有更新。 但是如果我 go 检查Bin/Debug并检查MusicPlayerDB.mdf ,数据就在那里。

解决此问题的最佳方法是什么? 我看到其他评论说要使用.mdf的绝对路径(或类似的东西),但如果可能的话,我想避免这种情况。

这是我的连接字符串,

private const String CONNECTION_STRING = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MusicPlayerDB.mdf;Integrated Security=True";

这是我的插入代码:

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

这就是预期的工作方式。 |数据目录| 在桌面应用程序中指向可执行文件的运行位置。 这意味着当您在 VS 内运行应用程序时bin\debugbin\release (工作文件夹),但当您在 VS 外运行应用程序时是安装文件夹。

这种安排允许您将空 MDF 保留在项目文件夹中,而工作副本保留在 output 文件夹中。 当您需要更改数据库架构中的某些内容时,您可以使用服务器资源管理器更改项目文件夹中的副本。 因此,文件的新副本将被复制到下一个 VS session 开头的 output 文件夹中。 当您需要分发您的应用程序时,您将 MDF 文件分发到您的项目文件夹中。

当然,如果您需要检查数据库的工作副本中发生了什么,那么您可以在服务器资源管理器中创建一个新连接,该连接指向工作文件夹中的 MDF 文件。

如果您需要更多控制,则可以更改替换字符串 |DataDirectory| 的位置。 点。 例如,请参阅此问题和我的答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM