Как выполнить другую команду SELECT после выполнения первой?

    protected void Button1_Click(object sender, EventArgs e)
    {
        string client = TextBox1.Text;
        string selected = RadioButtonList1.SelectedValue;
        string calendar = Calendar1.SelectedDate.ToShortDateString();
        string disease = txtDisease.Text;

        SqlCommand insert = new SqlCommand("insert into Appointment(Client_ID, DateofAppointment, TimeofAppointment, Disease) values(@Client_ID, @DateofAppointment, @TimeofAppointment, @Disease)", conn);
        try
        {
            conn.Open();

            SqlCommand cmd = new SqlCommand("select * from Client where Client_ID = @Client_ID", conn);
            cmd.Parameters.AddWithValue("@Client_ID", TextBox1.Text);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {       
                    insert.Parameters.AddWithValue("@Client_ID", client);
                    insert.Parameters.AddWithValue("@DateofAppointment", calendar);
                    insert.Parameters.AddWithValue("@TimeofAppointment", selected);
                    insert.Parameters.AddWithValue("@Disease", disease);
                    insert.ExecuteNonQuery();
                    TextBox1.Text = "";
                    RadioButtonList1.SelectedIndex = -1;
                    txtDisease.Text = "";
                    ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Appointment submitted! Please wait for your SMS confirmation. Thank you!')</script>");
            }
            else
            {
                TextBox1.Text = "";
                RadioButtonList1.SelectedIndex = -1;
                txtDisease.Text = "";
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('You are not a registered client!')</script>");
            }
        }
        catch
        {
            conn.Close();
        }

    }


}

Я хочу создать другую команду для поиска, если дата и галстук уже заняты, прежде чем вставить ее в мою базу данных.

3 ответа

Не знаю, какое было ваше первоначальное исключение, но полезно указать это при публикации вопроса.

Также, что касается вашего соединения, соединения на уровне класса обычно не рекомендуются. Sql Server обрабатывает пул соединений для вас, поэтому рекомендуется утилизировать ваше соединение, как только вы его используете. Если вы хотите сделать запрос (в другом методе или классе), создайте новое соединение. Также оберните ваши связи в using блоки для обеспечения их закрытия и утилизации.

А что касается вашей даты, то лучше всегда сохранять данные в своем родном типе. Это означает, что тип вашей колонки для вашей даты должен быть Sql Date, а не строкой. Это также означает, что значение вашего параметра для вашего календаря должно быть DateTime calendar = Calendar1.SelectedDate; и не string,

protected void Button1_Click(object sender, EventArgs e)
{
    string client = TextBox1.Text;
    string selected = RadioButtonList1.SelectedValue;

    // this should be a DateTime instance, not a string
    string calendar = Calendar1.SelectedDate.ToShortDateString();

    string disease = txtDisease.Text;

    try
    {
        conn.Open();

        SqlCommand cmd = new SqlCommand("select 1 from Appointment WHERE DateofAppointment = @DateofAppointment AND TimeofAppointment = @TimeofAppointment", conn);
        cmd.Parameters.AddWithValue("@DateofAppointment", calendar);
        cmd.Parameters.AddWithValue("@TimeofAppointment", selected);
        bool exists = false;
        using(var reader = cmd.ExecuteReader()) {
           exists = reader.Read(); // if this returns true there is a record
        }

        // do something based on exists

        SqlCommand insert = new SqlCommand("insert into Appointment(Client_ID, DateofAppointment, TimeofAppointment, Disease) values(@Client_ID, @DateofAppointment, @TimeofAppointment, @Disease)", conn);

        // repurpose same pointer but to different instance
        cmd = new SqlCommand("select * from Client where Client_ID = @Client_ID", conn);
        cmd.Parameters.AddWithValue("@Client_ID", TextBox1.Text);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {       
                insert.Parameters.AddWithValue("@Client_ID", client);
                insert.Parameters.AddWithValue("@DateofAppointment", calendar);
                insert.Parameters.AddWithValue("@TimeofAppointment", selected);
                insert.Parameters.AddWithValue("@Disease", disease);
                insert.ExecuteNonQuery();
                TextBox1.Text = "";
                RadioButtonList1.SelectedIndex = -1;
                txtDisease.Text = "";
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Appointment submitted! Please wait for your SMS confirmation. Thank you!')</script>");
        }
        else
        {
            TextBox1.Text = "";
            RadioButtonList1.SelectedIndex = -1;
            txtDisease.Text = "";
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('You are not a registered client!')</script>");
        }
    }
    catch
    {
        conn.Close();
    }
}

protected void Button1_Click(отправитель объекта, EventArgs e) {строка client = TextBox1.Text; строка selected = RadioButtonList1.SelectedValue; string calendar = Calendar1.SelectedDate.ToShortDateString(); строка болезнь = txtDisease.Text;

        SqlCommand insert = new SqlCommand("insert into Appointment(Client_ID, DateofAppointment, TimeofAppointment, Disease) values(@Client_ID, @DateofAppointment, @TimeofAppointment, @Disease)", conn);
        try
        {
            conn.Open();

            SqlCommand cmd = new SqlCommand("select * from Client where Client_ID = @Client_ID", conn);
            cmd.Parameters.AddWithValue("@Client_ID", TextBox1.Text);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                SqlCommand search = new SqlCommand("select * from Appointment where DateofAppointment = @DateofAppointment and TimeofAppointment = @TimeofAppointment", conn);
                search.Parameters.AddWithValue("@DateofAppointment", calendar);
                search.Parameters.AddWithValue("@TimeofAppointment", selected);
                Int32 count = (Int32)search.ExecuteScalar();
                if (count > 0)
                {
                    ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Error!')</script>");
                }
                else
                {
                    insert.Parameters.AddWithValue("@Client_ID", client);
                    insert.Parameters.AddWithValue("@DateofAppointment", calendar);
                    insert.Parameters.AddWithValue("@TimeofAppointment", selected);
                    insert.Parameters.AddWithValue("@Disease", disease);
                    insert.ExecuteNonQuery();
                    TextBox1.Text = "";
                    RadioButtonList1.SelectedIndex = -1;
                    txtDisease.Text = "";
                    ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Appointment submitted! Please wait for your SMS confirmation. Thank you!')</script>");
                }
            }
            else
            {
                TextBox1.Text = "";
                RadioButtonList1.SelectedIndex = -1;
                txtDisease.Text = "";
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('You are not a registered client!')</script>");
            }
        }
        catch
        {
            conn.Close();
        }

    }


}

Это все еще не работает...:(

Вы можете создать команду перед первой и проверить результат перед выполнением второй:

cmd.CommandText = "SELECT COUNT(*) FROM Client where {you conditions}";
Int32 count = (Int32) cmd.ExecuteScalar();

А затем проверьте, если count больше 0, затем выполнить второе.

Другие вопросы по тегам