C# - ConnectionString 属性尚未初始化

标签 c#

我刚学c#。我正在尝试在 c# windows 窗体中制作简单的 CRUD,但那里出现了一些错误。错误提示 The ConnectionString property has not been initialized. 下面的代码显示了我是如何尝试的。

App.config 用于连接 SQL SERVER

<connectionStrings>
<add name="connectionstr" connectionString="Data Source=DESKTOP-F8UCLUB;Initial Catalog=bug_tracker;Integrated Security=True" />

DBConnection

class DBConnection
{
    private string connectionString = ConfigurationManager.ConnectionStrings["connectionstr"].ConnectionString;

    public SqlConnection GetConnection()
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            return connection;
        }
    }
}

插入函数

 public void Insert(Programmer t)
    {
        conn.Open();
        IDbTransaction trans = null;

        try
        {
            conn.BeginTransaction();

            SqlCommand sql = new SqlCommand(null, conn);
            sql.CommandText = "INSERT INTO tbl_programmer VALUES(@fullName, @username, @password)";
            sql.Parameters.AddWithValue("@fullName", t.FullName);
            sql.Parameters.AddWithValue("@username", t.Username);
            sql.Parameters.AddWithValue("@password", t.Password);

            sql.Prepare();
            sql.ExecuteNonQuery();

            trans.Commit();
        }
        catch (SqlException ex)
        {
            trans.Rollback();
            throw ex;
        }
        finally
        {
            conn.Close();
        }
    }

最佳答案

The problem is using keyword. using directive only be use disposable objects.

If you create any instance in using block, the instance disposible out of curly braces..

 public SqlConnection GetConnection()
    {
        SqlConnection connection = new SqlConnection(connectionString);
            if (connection.State == ConnectionState.Closed)                
                connection.Open();

            return connection;            
    }

关于C# - ConnectionString 属性尚未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50190997/

相关文章:

c# - 使用此格式转换日期时间字符串 : (yyyy-MM-dd'T'hh:mm:ss-zzz)

c# - 值类型如何实现接口(interface)类型?

c# - 如何通过引用修改该字符串的非托管 C 库来发送字符串?

C# 捕捉麦克风

c# - C++ 在 Visual Studio 2010 中从二进制文件读取 void* 数据作为 utf8

c# - 使用 Windows 传真发送和接收传真

c# - 使用SoundPlayer在C#中播放.wav文件

c# - StreamReader 行和行分隔符

c# - KeyDown 事件中无法识别 F7 键

c# - linq 案例陈述