【问题标题】:update Windows Form Connection string from local db for other users从本地数据库为其他用户更新 Windows 窗体连接字符串
【发布时间】:2019-11-24 04:07:30
【问题描述】:

我确实查看了该网站上的其他几篇帖子并提出了以下解决方案,但没有成功。我将连接字符串放入 app.config 文件中,并将配置管理代码添加到应用程序代码中。如果删除应用程序中从本地数据库读取连接字符串的代码的配置管理行,应用程序可以正常工作。

app.config 文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
  <connectionStrings>
    <add name="Test" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\cvyc8\Documents\Test.mdf;Integrated Security=True;Connect Timeout=30" />
  </connectionStrings>
</configuration>

应用代码

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

namespace Week_4_Test
{
    public partial class Form1 : Form
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\cvyc8\Documents\Test.mdf;Integrated Security=True;Connect Timeout=30");
        int Id = 0;
        public Form1()
        {
            InitializeComponent();
            string conStr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
            var connection =
            System.Configuration.ConfigurationManager.
            ConnectionStrings["Test"].ConnectionString;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (con.State == ConnectionState.Closed)
                    con.Open();
                if (btnSave.Text == "Save")
                {
                    SqlCommand sqlCmd = new SqlCommand("MemberAddorEdit", con);
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@mode", "Add");
                    sqlCmd.Parameters.AddWithValue("@Id", 0);
                    sqlCmd.Parameters.AddWithValue("@Name", txtName.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@PhoneNumber", txtNumber.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
                    sqlCmd.ExecuteNonQuery();
                    MessageBox.Show("Save Successful");
                }
                else
                {
                    SqlCommand sqlCmd = new SqlCommand("MemberAddorEdit", con);
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@mode", "Edit");
                    sqlCmd.Parameters.AddWithValue("@Id", Id);
                    sqlCmd.Parameters.AddWithValue("@Name", txtName.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@PhoneNumber", txtNumber.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
                    sqlCmd.ExecuteNonQuery();
                    MessageBox.Show("Updated Successful");
                }
                Reset();
                FillDataGridView();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error Message");
            }
            finally
            {
                con.Close();
            }
        }

        void FillDataGridView()
        {
            if (con.State == ConnectionState.Closed)
                con.Open();

            SqlDataAdapter sqlDA = new SqlDataAdapter("MemberDisplayorSearch", con);
            sqlDA.SelectCommand.CommandType = CommandType.StoredProcedure;
            sqlDA.SelectCommand.Parameters.AddWithValue("@Name", txtSearch.Text.Trim());
            DataTable dTbl = new DataTable();
            sqlDA.Fill(dTbl);
            dataGridView1.DataSource = dTbl;
            con.Close();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                FillDataGridView();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error Message");
            }
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow.Index != -1)
            {
                Id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value.ToString());
                txtName.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
                txtNumber.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
                txtAddress.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
                btnSave.Text = "Edit";
                btnDelete.Enabled = true;
            }
        }

        void Reset()
        {
            txtName.Text = txtNumber.Text = txtAddress.Text = "";
            btnSave.Text = "Save";
            Id = 0;
            btnDelete.Enabled = false;
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            Reset();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Reset();
            FillDataGridView();

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (con.State == ConnectionState.Closed)
                    con.Open();

                    SqlCommand sqlCmd = new SqlCommand("MemberDelete", con);
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@Id", Id);
                    sqlCmd.ExecuteNonQuery();
                    MessageBox.Show("Deleted Successful");
                Reset();
                FillDataGridView();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error Message");
            }
        }
    }
}

【问题讨论】:

  • 看起来您从 app.config 文件中获取了连接字符串,但您从未使用它来实际打开连接。尝试在Form1 构造函数的末尾添加con = new SqlConnection(connection)

标签: c# winforms connection


【解决方案1】:

您从构造器中的配置文件中读取连接字符串的代码是正确的。您在创建表单时创建一个带有常量字符串的 SqlConnection。您永远不会将读取连接 string 输入到您的 SqlConnection 实例中。

有两个选项可以纠正这一点:将 SqlConnection 的创建移至构造函数或设置 SqlConnection 实例的 connectionstring 属性。

选项 1:将 SqlConnection 的创建移至构造函数

public partial class Form1 : Form
{
    readonly SqlConnection con; // readonly as we want to keep that one connection around.
    int Id = 0;
    public Form1()
    {
        InitializeComponent();
        string conStr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
        con = new SqlConnection(conStr);
    }

选项 2:设置 SqlConnection 的 connectionString 属性

请注意,我在此处保留了 SqlConnection 构造函数调用,其值未受影响,但它不再有任何用途,最好将其删除。我不想优化或引入太多可能会让您感到困惑的更改。

public partial class Form1 : Form
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\cvyc8\Documents\Test.mdf;Integrated Security=True;Connect Timeout=30"); // this can be the default ctor.
    int Id = 0;
    public Form1()
    {
        InitializeComponent();

        con.ConnectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
    }

另请参阅 SqlConnection 类型的 MSDN 连接。

选项 3:结合选项 1 和 2

public partial class Form1 : Form
{
    // assume we create and assign an instance once
    // so mark the var readonly
    readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
    int Id = 0;
    public Form1()
    {
        InitializeComponent();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    相关资源
    最近更新 更多