在本地SQL Server数据库和app.config中插入记录

时间:2016-09-08 17:39:20

标签: sql-server app-config windows-forms-designer

我正在尝试使用下面的C#代码将记录插入Users表。这是一个带有app.config的Windows窗体项目,并且记录似乎不会按预期添加到数据库中。知道为什么吗?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DemoDBConnection
{
   public partial class RegisterUser : Form
   {
       SqlConnection connection = 
          new SqlConnection(ConfigurationManager.ConnectionStrings
              ["DemoDBConnection"].ConnectionString);

       public RegisterUser()
       {
          InitializeComponent();
       }

       public void AuthenticateUser()
       {
           try
           {
               string insertQuery = 
                    "INSERT INTO Users (Username,Password) VALUES ('" +
                       this.txtUsername.Text + "','" + 
                       this.txtPassword.Text + "')";

               SqlCommand sqc = new SqlCommand(insertQuery, connection);

               connection.Open();
               sqc.ExecuteNonQuery();
               connection.Close();

               MessageBox.Show("Record Added Successfully");
           }
           catch (Exception ex)
           {
                MessageBox.Show("Record Can Not Successfully" + ex.Message);
           }
    }

    private void btnRegister_Click(object sender, EventArgs e)
    {
        AuthenticateUser();
    }
}

我的app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="DemoDBConnection"
             connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\App_Data\DemoDB.mdf;Integrated Security=True"
             providerName="System.Data.SqlClient" />
     </connectionStrings>
</configuration>

0 个答案:

没有答案