none
Sqldatareader RRS feed

  • 问题

  • 请问使用Sqldatareader执行数据检索后,在检索完成时Sqldatareader是否会自动关闭数据连接,如果不能请问怎么办,以下是我自己写的一段代码,请大家不吝赐教。谢谢!

    该段代码是希望从数据库中读取编号,并生成一个新编号。请多多指教。再次谢谢了。

            private void NewCustomerID()
            {
                string Sql = "SELECT TOP 1 ID, Customer_ID FROM tb_Customer ORDER BY ID DESC";
                SqlCommand Cmd = new SqlCommand(Sql, Sqlstr.GetCon());
                SqlDataReader dr = Cmd.ExecuteReader();
                dr.Read();
                if (dr.HasRows)
                {
                    MaxCustomerID = Convert.ToInt32(dr["Customer_ID"].ToString().Substring(1, 4).ToString());
                    MaxCustomerID++;
                    txt_CustomerID.Text = string.Format("A{0}", MaxCustomerID.ToString().PadLeft(4, '0'));
                }
                else
                {
                    MaxCustomerID = 1;
                    txt_CustomerID.Text = string.Format("A{0}", MaxCustomerID.ToString().PadLeft(4, '0'));
                }
            }
    2009年12月1日 13:48

答案

  • 不会,要调用Close()。请参考msdn中的代码

    public void ReadMyData(string myConnString) {
        string mySelectQuery = "SELECT OrderID, CustomerID FROM Orders";
        SqlConnection myConnection = new SqlConnection(myConnString);
        SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection);
        myConnection.Open();
        SqlDataReader myReader;
        myReader = myCommand.ExecuteReader();
        // Always call Read before accessing data.
        while (myReader.Read()) {
           Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1));
        }
        // always call Close when done reading.
        myReader.Close();
        // Close the connection when done with it.
        myConnection.Close();
     }
    

    I Love SQL Server!
    2009年12月2日 3:15