Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

sql server - C# Database The ConnectionString property has not been initialized

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();
    }

Here is the code in my button:

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();

and here is my stored procedures:

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

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#.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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();
    }
}

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

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

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();
       }
    }

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...