1. 程式人生 > >C# SqlCommand 資料庫連線操作

C# SqlCommand 資料庫連線操作

//資料庫操作
             string strcon = "server = localhost,1433;uid = sa; pwd = 123456; database = MyDataBase";
             string strSQL = "select Name,Chinese,Math,English from Student where Name = @name";
             SqlConnection con = new SqlConnection(strcon);
             SqlCommand cmd = new SqlCommand(strSQL, con);
             cmd.Parameters.Add("@name", SqlDbType.VarChar);
             cmd.Parameters["@name"].Value = Name;
             DataSet ds = new DataSet();
             try
             {
                 SqlDataAdapter DA = new SqlDataAdapter(cmd);
                 DA.Fill(ds, "tb");
             }
             catch (SqlException E)
             {
                 throw new Exception(E.Message);
             }
             con.Close();//關閉資料庫

這是完整的SqlCommand 連線資料、從資料庫取資料的程式碼,重點說一下SqlCommand :

其實這段程式碼也可以這樣寫:

 //資料庫操作
            string strcon = "server = localhost,1433;uid = sa; pwd = 123456; database = MyDataBase";
            string strSQL = "select Name,Chinese,Math,English from Student where Name = '" + Name + "'";
            SqlConnection con = new SqlConnection(strcon);
            DataSet ds = new DataSet();
            try
            {
                SqlDataAdapter DA = new SqlDataAdapter(strSQL, con);
                DA.Fill(ds, "tb");
            }
            catch (SqlException E)
            {
                throw new Exception(E.Message);
            }
            con.Close();//關閉資料庫

也就說,sql引數用字串拼接的方式,但是字串拼接有sql注入的危險,另外程式碼顯得不專業,所以推薦使用填充引數的方法。

回到原話題,就是看看SqlCommand cmd連結資料庫,都需要填充哪些?

VS檢視變數:

CommandText就是sql語句,Parameters就是填充的引數,Parameters[0]就是第一個引數,Parameters[1]是第二個引數...

展開ResultView:

看到這,應該對SqlCommand有所瞭解。

所以,寫程式碼的時候就可以靈活運用。比如,可以這樣寫:

 //資料庫操作
            string strcon = "server = localhost,1433;uid = sa; pwd = 123456; database = MyDataBase";
            string strSQL = "select Name,Chinese,Math,English from Student where Name = @name";


            //先建立cmd物件
            SqlCommand cmd = new SqlCommand(strSQL);
            cmd.Parameters.Add("@name", SqlDbType.VarChar);
            cmd.Parameters["@name"].Value = Name;

            //後建立連線物件
            SqlConnection con = new SqlConnection(strcon);
            cmd.Connection = con;//連線物件賦值給cmd的連線物件
            DataSet ds = new DataSet();
            try
            {
                
                SqlDataAdapter DA = new SqlDataAdapter(cmd);
                DA.Fill(ds, "tb");
            }
            catch (SqlException E)
            {
                throw new Exception(E.Message);
            }
            con.Close();//關閉資料庫

可以看出,Connection是SqlCommand內部的一個元素。

另外: SqlDataAdapter DA = new SqlDataAdapter(cmd);

              SqlDataAdapter DA = new SqlDataAdapter(strsql, con);

這個函式是過載的,可以傳cmd,也可以傳sql和con。

所以,舉一反三、發現其本質,方可靈活運用。