Or what's the recommended way to read and write at the same time? Having two connections open is the only way? This is on a plain Windows Forms C# (.NET 3.5) app
using (SqlConnection conn = new SqlConnection(connStr)) {
SqlCommand cmdRead = new SqlCommand("select stools from foo", conn);
SqlDataReader rdr = cmdRead.ExecuteReader();
SqlCommand cmdWrite = new SqlCommand("insert into bar values (@beer)", conn);
SqlParameter beer = new SqlParameter("@beer", SqlDbType.Int);
cmdWrite.Parameters.Add(beer);
while(rdr.Read()) {
int stools = rdr.GetInt32(0);
cmdWrite.Parameters["@beer"].value = stools;
//Next line fails for an open data reader associated to the "command"
cmdWrite.ExecuteNonQuery();
}
rdr.Close()
}
This, OTOH, works, but looks ugly to me (besides of opening an extra connection)
using (SqlConnection connR = new SqlConnection(connStr)) {
using (SqlConnection connW = new SqlConnection(connStr)) {
SqlCommand cmdRead = new SqlCommand("select stools from foo", connR);
SqlDataReader rdr = cmdRead.ExecuteReader();
SqlCommand cmdWrite = new
SqlCommand("insert into bar values (@beer)", connW);
SqlParameter beer = new SqlParameter("@beer", SqlDbType.Int);
cmdWrite.Parameters.Add(beer);
while(rdr.Read()) {
int stools = rdr.GetInt32(0);
cmdWrite.Parameters["@beer"].value = stools;
cmdWrite.ExecuteNonQuery();
}
rdr.Close()
}
}
In this simple case, read all the stools, store them in a list, close the reader and then write them will work (as long as there aren't many stools in the database), but in more complex cases it starts being unwieldy and memory hungry, so that's also not desirable.