C# ~ SQL query

an example query sql by SqlCommand, SqlDataReader, SqlConnection

------------------------------------------------------------------------------------------------
string sql = "select * from ggyy";

string connectString = ConfigurationManager.ConnectionStrings["ggyyConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectString);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
string qq = "";
try {
SqlDataReader r = cmd.ExecuteReader();

while (r.Read()) {
qq += (string)r["fieldName"].ToString();
}
r.Close();

} catch (Exception e) {
qq = e.Message;
}
conn.Close();
------------------------------------------------------------------------------------------------

first time i got message

ExecuteReader requires an open and available Connection. The connection's current state is closed.

because i didn't open the connection.....

conn.Open();

沒有留言: