连接字符串属性尚未初始化

时间:2013-02-22 13:20:59

标签: c# sql .net database

我有以下使用查询的方法,但是visual studio会抛出错误,如图所示。

private void FindOrderData()
        {
            int intOrder = int.Parse(frmInput.InvoiceOrder);

            string InvSql = "SELECT Orders.OrderID, Orders.OrderDate, Orders.Freight," +
                "Customers.CompanyName, Customers.City, " +
                "(Employees.FirstName + Space(1) + Employees.LastName) As Salesperson " +
                "FROM ((Orders " +
                "INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID) " +
                "INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID) " +
                "WHERE Orders.OrderID = " + "10655";

            OleDbConnection cnn = new OleDbConnection(strCon);
            OleDbCommand cmdOrder = new OleDbCommand(InvSql, cnn);
            cnn.Open();

            OleDbDataReader rdrOrder = cmdOrder.ExecuteReader();

            // Get CompanyName, City, Salesperson, OrderID, OrderDate and Freight
            rdrOrder.Read();
            CustomerName = rdrOrder["CompanyName"].ToString();
            CustomerCity = rdrOrder["City"].ToString();
            SellerName = rdrOrder["Salesperson"].ToString();
            SaleID = rdrOrder["OrderID"].ToString();
            System.DateTime dtOrder = Convert.ToDateTime(rdrOrder["OrderDate"]);
            SaleDate = dtOrder.ToShortDateString();
            SaleFreight = Convert.ToDecimal(rdrOrder["Freight"]);
            // Get invoice total
            GetInvoiceTotal();

            rdrOrder.Close();
            cnn.Close();
        }

enter image description here

string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Amrit\\Desktop\\Northwind.mdb ;Persist Security Info=False;";

3 个答案:

答案 0 :(得分:4)

您需要将strCon分配给正确的连接字符串。此变量的值很可能是nullempty

例如:

strCon = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
OleDbConnection cnn = new OleDbConnection(strCon);

您可以在以下位置找到所需的连接字符串:

http://connectionstrings.com/

答案 1 :(得分:0)

如果您从其他地方复制了此代码,那么您错过了定义strCon的行。它应该像... ...

string strCon = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"

答案 2 :(得分:0)

请停止对此进行推测,如MVP .....,

我可以用强点重现,如果发生了异常,如果你已经回滚了你的事务,并尝试继续进一步的数据检索,Connection就会被关闭,所以错误。

如果您想了解有关您的错误的更多详细信息,请在VS IDE中将异常保持为ON。 (调试 - >异常,检查异常......)你会看到导致此错误的脏代码!

Hydtechie