c#代码获取数组中的选定查询结果

时间:2014-06-06 09:36:29

标签: c# sql sql-server

我想在数组中获取SQL Select查询结果,或者在阅读结果时我想在表中进行更新或插入...请有人帮助我。我的代码在

之下
    private void updateNewTask()
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString);
        GetCurrentDate();
        DateTime myDateTime = DateTime.Now;
        string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
        string UserDate = DateTime.Now.ToUniversalTime().AddMinutes(DateTime.Now.Subtract(DateTime.Now.ToUniversalTime()).TotalMinutes).ToString("yyyy/MM/dd HH:MM:SS");
        string sql = "SELECT Recurring_Id FROM Master_Recurring where Recurring_Id Not in" +
                " (SELECT Recurring_Id FROM Master_Recurring WHERE Last_Completed < '" + lblServerDate + "' ANd Recurring_Active='True')";     
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.Connection = connection;
        connection.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Recurrid = reader["Recurring_Id"].ToString();
                GetRecurringDetails();                                     
            }
            connection.Close();


        }
        else
        {
            Console.WriteLine("No rows found.");
        }
        reader.Close();
        connection.Close();
    }

    private void GetRecurringDetails()
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString);
        string sql = "select * from Master_Recurring where Recurring_Id='" + Recurrid + "'";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.Connection = connection;
        connection.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Empcode = reader["Emp_Code"].ToString();
                TaskTitle = reader["Task_Title"].ToString();
                TaskMsg = reader["Task_Message"].ToString();
                TaskPriority = reader["Task_Priority"].ToString();
                TaskLogincode = reader["Task_Login_code"].ToString();
                TaskLoginName = reader["Task_Login_name"].ToString();
                Recurringcount = reader["Recurring_Count"].ToString();
                Totcount = reader["Total_Count"].ToString();                            
            }

        }
        else
        {
            Console.WriteLine("No rows found.");
        }
        reader.Close();
        connection.Close();
    }

这是获取连接打开错误...

2 个答案:

答案 0 :(得分:0)

connection.Open();被调用两次,'updateNewTask'方法调用'GetRecurringDetails();'再次调用connection.Open();

答案 1 :(得分:0)

在再次打开连接之前,请务必检查连接状态。

if (connection.State == ConnectionState.Closed)
{
     connection.Open();
}