这是我的代码。我试图获得存储在query1
变量中的SQL查询的结果,并希望将该结果用于存储在query
变量中的SQL查询中。 Messagebox是无关紧要的,我只是编写它以查看我是否从listbox1获得了正确的结果。如果我将query1的结果硬编码为命令参数,它可以很好地工作。
private void btnAddCoarse_click(object sender, EventArgs e)
{
MessageBox.Show(listBox1.SelectedItem.ToString());
string query1 ="SELECT ogrenciNo FROM ders,ogrenci,Enrollment WHERE ogrenciId=ogrenciNo AND dersId=dersKodu AND ogrenci.email='" + mainform.Username + "' AND Enrollment.dersId='"+listBox1.SelectedValue+"'";
string query = "INSERT INTO Enrollment(dersId,ogrenciId) VALUES (@dersId, @ogrenciId)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("@dersId", listBox1.SelectedValue);
command.Parameters.AddWithValue("@ogrenciId",//this is where i need the query1//);
command.ExecuteNonQuery();
PopulateList2();
}
}
答案 0 :(得分:2)
您只需要一个sql命令。结构将是这样的:
insert into table2
(field1, field2)
select value1, value2
etc
答案 1 :(得分:1)
int id;
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query1, connection))
{
connection.Open();
id = Convert.ToInt32(command.ExecuteScalar()); //I guess it returns only 1 id?..
}
答案 2 :(得分:0)
尝试这样做
private void btnAddCoarse_click(object sender, EventArgs e)
{
//MessageBox.Show(listBox1.SelectedItem.ToString());
string query1 ="SELECT ogrenciNo FROM ders,ogrenci,Enrollment WHERE ogrenciId=ogrenciNo AND dersId=dersKodu AND ogrenci.email='" + mainform.Username + "' AND Enrollment.dersId='"+listBox1.SelectedValue+"'";
string query = "INSERT INTO Enrollment(dersId,ogrenciId) VALUES (@dersId, @ogrenciId)";
using (connection = new SqlConnection(connectionString))
{
int result=0;
using (SqlCommand command = new SqlCommand(query1, connection))
{
connection.Open();
result=Convert.ToInt32(command.ExecuteScalar());
connection.Close();
}
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("@dersId", listBox1.SelectedValue);
command.Parameters.AddWithValue("@ogrenciId",result);
command.ExecuteNonQuery();
PopulateList2();
}
}
}