数据库记录保存在bin文件夹而不是项目文件夹中

时间:2019-06-17 17:57:22

标签: c# .net visual-studio windowsformshost

我正在尝试保存一些有关用户的记录,但是这些记录保存在bin文件夹中而不是项目文件夹中。因此,当我插入新记录时,该记录不会保存在我想要的位置!

我试图通过更改connectionString来解决它,但是它不起作用。

我的App.config文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="Battle_Tank.Properties.Settings.UsersDatabaseConnectionString"
            connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UsersDatabase.mdf;Integrated Security=True;Connect Timeout=30"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>

初始化connectionString:

string connectionString;
        public Form1()
        {
            InitializeComponent();
            connectionString = ConfigurationManager.ConnectionStrings["Battle_Tank.Properties.Settings.UsersDatabaseConnectionString"].ConnectionString;
        }

添加新记录

private void btnRegister_Click(object sender, EventArgs e)
        {
            string query = "INSERT INTO Users VALUES(@UserName, @UserPassword, 0)";

            using (connection = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                connection.Open();

                if (tbUsername.Text == "")
                {
                    MessageBox.Show("Username Cannot be empty");
                    tbUsername.Focus();
                    return;
                }
                command.Parameters.AddWithValue("@UserName", tbUsername.Text);
                command.Parameters.AddWithValue("@UserPassword", tbPassword.Text);
                //   command.Parameters.AddWithValue("@Points", 0);

                command.ExecuteNonQuery();
            }

            MessageBox.Show("User Registered Succesfully");
        }

0 个答案:

没有答案