ADO.net--杂七杂八(一)

 private void BtnConnectDataBase_Click(object sender, RoutedEventArgs e)
        {
            string connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=Easy5DB; User ID=easy5;Password=123456";
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                try
                {
                    sqlConnection.Open();
                    using (SqlCommand commnad = sqlConnection.CreateCommand())
                    {
                        try
                        {
                            string query = "select genreId, name from inventory.Genre order by genreId";
                            commnad.CommandText = query;
                            //-------------SqlDataReader
                            //SqlDataReader dataReader = commnad.ExecuteReader();
                            //while (dataReader.Read())
                            //{
                            //    Console.WriteLine("{0}-{1}", dataReader["genreId"], dataReader["name"]);
                            //}
                            //--------------SqlDataAdapter
                            SqlDataAdapter dataAdapeter = new SqlDataAdapter(commnad);
                            DataSet dataSet = new DataSet();
                            dataAdapeter.Fill(dataSet);
                            //dataSet.Tables
                            foreach (DataRow row in dataSet.Tables[0].Rows)
                            {
                                Console.WriteLine("{0}-{1}",row["genreId"],row["name"]);
                            }
                        }
                        catch (Exception commandError)
                        {
                            MessageBox.Show("执行Command失败:\n" + commandError.ToString());
                        }

                    }
                }
                catch (Exception openError)
                {
                    MessageBox.Show("打开数据库失败:\n" + openError.ToString());
                }
                finally
                {
                    sqlConnection.Close();
                }

            }
        }

 

posted @ 2013-06-28 11:41  easy5  阅读(157)  评论(0编辑  收藏  举报