C# 数据库 ConnectionString 属性尚未初始化 [英] C# Database The ConnectionString property has not been initialized

查看:37
本文介绍了C# 数据库 ConnectionString 属性尚未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的数据库中插入值,每当我尝试添加它时,我的程序就会崩溃,给我一个错误,即 ConnectionString 属性尚未初始化,但我正确初始化了它.这是我的代码:

I'm trying to insert values in my database and whenever I try to add it, my program just crash, giving me an error that The ConnectionString property has not been initialized, but I properly initialise it. Here is my code:

private static string conStr = @"Data Source=(LocalDB)v11.0;AttachDbFilename=c:usersaldrindocumentsvisual studio 2013ProjectsMidtermAssignment_RamirezMidtermAssignment_RamirezMasterFile.mdf;Integrated Security=True";
    SqlConnection myCon = new SqlConnection();

    private int studId, year, units; 
    private string fName, lName, mName, course, payment;

    public void insertRecord()
    {
        myCon.Open();
        SqlCommand insertInfo = new SqlCommand("spInsertStudentInformation", myCon);
        insertInfo.CommandType = CommandType.StoredProcedure;
        insertInfo.Parameters.Add("@studId", SqlDbType.Int).Value = studId;
        insertInfo.Parameters.Add("@fName", SqlDbType.VarChar).Value = fName;
        insertInfo.Parameters.Add("@lName", SqlDbType.VarChar).Value = lName;
        insertInfo.Parameters.Add("@mName", SqlDbType.VarChar).Value = mName;
        insertInfo.ExecuteNonQuery();
        myCon.Close();
        myCon.Open();
        SqlCommand insertData = new SqlCommand("spInsertStudentData", myCon);
        insertData.CommandType = CommandType.StoredProcedure;
        insertData.Parameters.Add("@studId", SqlDbType.Int).Value = studId;
        insertData.Parameters.Add("@course", SqlDbType.VarChar).Value = course;
        insertData.Parameters.Add("@year", SqlDbType.Int).Value = year;
        insertData.Parameters.Add("@units", SqlDbType.Int).Value = units;
        insertData.Parameters.Add("@payment", SqlDbType.VarChar).Value = payment;
        insertData.ExecuteNonQuery();
        myCon.Close();
    }

这是我按钮中的代码:

myData.StudId = Convert.ToInt32(txtStudId.Text);
        myData.FName = txtFName.Text;
        myData.LName = txtLName.Text;
        myData.MName = txtMName.Text;
        myData.Course = cboCourse.SelectedItem.ToString();
        myData.Year = Convert.ToInt32(cboYear.SelectedItem.ToString());
        myData.Units = Convert.ToInt32(txtUnits.Text);
        myData.Payment = cboPayment.SelectedItem.ToString();
        myData.insertRecord();

这是我的存储过程:

CREATE PROCEDURE [dbo].spInsertStudentData
@studId int,
@course varchar(50),
@year int,
@units int,
@payment varchar(50)
AS
    INSERT INTO StudentData VALUES (@studId, @course, @year, @units, @payment)
RETURN 0

CREATE PROCEDURE [dbo].spInsertStudentInformation
@studId int,
@fName varchar(50),
@lName varchar(50),
@mName varchar(50)
AS
    INSERT INTO StudentInformation VALUES (@studId, @fName, @lName, @mName)
RETURN 0

我最近在 ASP.NET 中研究数据库,这就是我正在做的事情,但我不知道为什么这在 C# 中运行不正常.

I'm studying databases recently in ASP.NET and this is what I'm doing, but I don't know why this is not running fine in C#.

推荐答案

错误信息很明确.SqlConnection 对象在尝试打开连接之前需要一个连接字符串.因此,当您构建连接时,您在打开之前传递 connectionstring 或设置 ConnectionString 属性.

The error message is clear. An SqlConnection object needs a connectionstring before trying to open the connection. So when you build the connection you pass the connectionstring or set the ConnectionString property before opening.

但我真的建议你开始使用本地连接变量而不是全局变量.并将此声明保存在 using 语句中

But I really suggest you to start using local connection variables instead of global ones. And keep this declaration inside a using statement

private static string conStr = @".....";
public void insertRecord()
{
    using(SqlConnection myCon = new SqlConnection(conStr))
    using(SqlCommand insertInfo = new SqlCommand("spInsertStudentInformation", myCon))
    {
        myCon.Open();
        insertInfo.CommandType = CommandType.StoredProcedure;
        ....
        insertInfo.ExecuteNonQuery();

        // No need to close the connection here....


        SqlCommand insertData = new SqlCommand("spInsertStudentData", myCon);
        insertData.CommandType = CommandType.StoredProcedure;
        ....
        insertData.ExecuteNonQuery();
    }
}

SqlConnection 使用 连接池 基础结构,因此更好具有可以由连接池回收的局部变量,而无需为您的程序锁定重要资源

The SqlConnection uses the Connection Pooling infrastructure and thus is better to have local variables that can be recycled by the pool of connection without keeping an important resource locked for your program

最后,using 语句 避免了危险的内存泄漏关闭和处理像连接和命令这样的一次性对象也是在异常情况下

Finally the using statement avoids dangerous memory leaks closing and disposing the disposable objects like the connection and the command also in case of exceptions

在您的代码中还有一点需要注意.您执行两个相关的命令.如果由于某种原因您无法插入学生数据,我相信您不想插入学生信息.这些场景需要打开一个 SqlTransaction 来保持您的数据原子(这意味着如果任何操作失败,您不希望更改数据库中的任何内容)>

There is another point to note in your code. You execute two related commands. I am sure that you don't want to insert the student info if, for some reason, you are not able to insert the student data. These scenarios call for the opening of a SqlTransaction that keeps your data atomic (meaning that you don't want to change anything in the database if any the operations fail)

    using(SqlConnection myCon = new SqlConnection(conStr))
    using(SqlCommand insertInfo = new SqlCommand("spInsertStudentInformation", myCon))
    {
        myCon.Open();
        using(SqlTransaction ts = myCon.BeginTransaction())
        {
           insertInfo.CommandType = CommandType.StoredProcedure;
           insertInfo.Transaction = ts;
           ....
           insertData.CommandType = CommandType.StoredProcedure;
           insertData.Transaction = ts;
           ....
           insertData.ExecuteNonQuery();
           ts.Commit();
       }
    }

最终的 Commit 将保留数据库中的所有内容,同时退出 using 块而不调用 Commit,将自动回滚对表所做的每个更改

The final Commit will persist everything in the database while, exiting the using block without calling the Commit, will automatically Rollback every change made to your tables

这篇关于C# 数据库 ConnectionString 属性尚未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆