一個簡單的撈取資料庫資料的範例語法
(一)
SqlConnection conn = new SqlConnection();
try
{
conn.ConnectionString = "Data Source=.\\SqlExpress;Initial Catalog=NorthWind;
Integrated Security=true";
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Order";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
............
}
reader.Close();
}
catch (SqlException b)
{
MessageBox.Show(b.Message);
}
finally
{
conn.Close();
}
(二)或是使用Using
Using(SqlConnection conn = new SqlConnection())
{
try
{
conn.ConnectionString = "Data Source=.\\SqlExpress;Initial Catalog=NorthWind;
Integrated Security=true";
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Order";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
............
}
reader.Close();
}
catch (SqlException b)
{
MessageBox.Show(b.Message);
}
}
沒有留言:
張貼留言