用SqlParameter 給SQL傳遞參數


1.數據訪問層

using的用法:

01.可以using System;導命名控空間

02.using 的語法結構

     using(變量類型  變量名 =new 變量類型())

     {

      }

案例:

03.using的原理

  為什么出了using所在的{},會自動回收對象。

 原因是當我們將要出{},系統自動調用了Dispose()方法。

 而在DISpose方法中是這么實現的

 2.哪些對象才可以使用Using回收!如:SqlConnection  Font 和File 也都可以使用using   因為他們實現了IDisposable接口

必須實現了IDisposable 接口的類型才可以使用using回收!  

 

  3.using回收的是托管還是非托管資源?

解析:什么是托管:所有的C#代碼都是被CLR監管,

   結論是using回收的是 非托管資源

 

2.會實現參數化SQL

  解析:username: ' or 1=1 --    pwd:sb

1.使用using釋放資源

Using釋放的是托管資源還是非托管資源?

 

解析:非托管,C#應用托管到.NET Framework.但是他可以釋放非托管資源。

1.using用法:

01.有人問,什么樣的的語句可以使用using管理??

官方人士解析:稀缺的資源,才需要using管理。接着有人問:what is less resource ?例如:Connection對象,IO流。

02.Dispose方法會自動調用Close()

要想讓一個類型可以通過using管理,該類型或者父類必須實現了IDisposable接口。

 

using(SqlConnection con=new SqlConnection)

{

   //本質上自動調用了Dispose方法

}

2.close()和dispose()區別?

解析:close()只是關閉連接,但是通道沒有銷毀,dispose()不僅把連接給關閉了,而且把通道也給銷毀了。

2.會使用SqlParameter給SQL傳遞參數

 

1.又有人問,菜鳥寫的程序,被SQL注入怎么辦??

官方人士解析:

     01.要想避免,就通過參數的方式,來書寫SQL語句

     02.通過存儲過程,存儲過程中使用參數

2.哪些年,童鞋們用過的@

解析:01.數據庫中@@error:全局變量

                 @num:局部變量,程序員自己定義的變量

      02.路徑轉義:@"D:\"

      03.在SQL語句中進行參數化查詢時,可以避免SQL注入

 

SqlParameter對象

在C#中獲取存儲過程的返回值

SqlParameter     para=new SqlParameter("@myresult",SqlDBType.Int);

para.Dirction=ParameterDirction.Output;

para.Value;

3.會使用ADO.NET調用存儲過程,包括SqlHelper類的使用

無參的存儲過程

帶輸入參數的存儲過程

帶輸入和輸出參數的存儲過程

4.con.CrateCommand()的用法

5.SQL語句中參數化模糊查詢寫法

解析:like '%'+@name+'%'

private void btnOK_Click(object sender, EventArgs e)
        {
            string str = "Data Source=.;initial catalog=MySchool;uid=sa;pwd=6375196";

            SqlConnection con = new SqlConnection(str);
            string sql = "select * from student where studentname like '%'+@name+'%'";
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = sql;
            cmd.Parameters.Add(new SqlParameter("@name", txtName.Text));
            SqlDataAdapter da=new SqlDataAdapter(cmd);
            DataSet ds=new DataSet();
            da.Fill(ds, "Info");
            dataGridView1.DataSource = ds.Tables[0];

        }

 

SQL注入

            //登錄按鈕 用戶名和密碼不對也可以成功登錄
            //1.1獲取到用戶名和密碼
            string uname = txtName.Text;
            string pwd = txtPwd.Text;
            //1.2發送SQL指令,拼接SQL方式
            string str = "Data Source=.;Initial Catalog=MySchool;uid=sa;";
            string sql = "select count(1) from student where studentName='" + uname + "' and Loginpwd='" + pwd + "'";
            SqlConnection con = new SqlConnection(str);
            SqlCommand cmd = new SqlCommand(sql, con);
            con.Open();
            int count = Convert.ToInt32(cmd.ExecuteScalar());
            if (count > 0)
            {
                MessageBox.Show("成功登錄!");
            }
            else
            {
                MessageBox.Show("失敗!");
            } 


            //用戶名輸入 ' or 1=1 --  密碼輸入 :隨便輸
            //SQL Server 查詢的語句是  select count(1) from student where studentName='' or 1=1 --' and Loginpwd='sb
           

為防止SQL注入

            //1.1獲取到用戶名和密碼
            string uname = txtName.Text;
            string pwd = txtPwd.Text;
            //1.2發送SQL指令,拼接SQL方式
            string str = "Data Source=.;Initial Catalog=MySchool;uid=sa;";
            string sql = "select count(1) from student where studentName=@name and loginpwd=@pwd";
            SqlConnection con = new SqlConnection(str);
            SqlCommand cmd = new SqlCommand(sql, con);

            con.Open();
            SqlParameter p1 = new SqlParameter("@name", uname);
            SqlParameter p2 = new SqlParameter("@pwd", pwd);
            cmd.Parameters.Add(p1);
            cmd.Parameters.Add(p2);
            try
            {
                int count = Convert.ToInt32(cmd.ExecuteScalar());
                if (count > 0)
                {
                    MessageBox.Show("成功登錄!");
                }
                else
                {
                    MessageBox.Show("失敗!");
                }

            }
            catch (Exception)
            {

                // throw;
            } 

 C#調用帶輸入參數的存儲過程

數據庫--->可編程性--->存儲過程--->

//開始把Alter改成如下的create
create procedure usp_selectInfoOutput
@sex nvarchar(32),
@count int output
as
select * from Student where gender=@sex
select @count=count(1) from student
where gender=@sex
return 100

按性別加載數據

在Main窗體中寫

//1.1  連接字符串
            string str = "data source=.;initial catalog=MySchool;uid=sa;";
            //1.2 創建連接對象    呵呵
            SqlConnection con = new SqlConnection(str);
            //創建SqlCommand 對象的第二種方式
            //從Con出發
            //1.3  從連接對象構建命令對象
            SqlCommand cmd = con.CreateCommand();
            //1.4  給命令對象需要執行的SQL語句賦值
            cmd.CommandText = "usp_selectInfo";
            //告訴SQL引擎我傳遞過來的是        存儲過程的名稱
            //1.5  我們告訴SQL引擎   我通過網線送過去的字符串是  一個存儲過程的名字啊
            cmd.CommandType = CommandType.StoredProcedure;
            //1.6   構建存儲過程的輸入參數,並且給參數賦值,
            //參數的名稱必須和定義存儲過程的輸入參數名稱完成相同
            SqlParameter para = new SqlParameter("@sex", "1");
            //1.7   將參數和命令對象的參數集合綁定
            cmd.Parameters.Add(para);
            //1.8  打開數據庫連接通道真正建立
            con.Open();
            //1.9   構建一個適配器 )卡車( 對象
            SqlDataAdapter da = new SqlDataAdapter();
            //1.10  將已經初始化好的cmd對象和da綁定
            da.SelectCommand = cmd;
            //1.11   構建內存中的數據集對象
            DataSet ds = new DataSet();
            //1.12   從DB   拎    數據到DataSet 中的一張表
            da.Fill(ds, "StuInfo");
            //1.13    將dgv的數據源指向表
            dgvList.DataSource = ds.Tables["StuInfo"];
            //1.14    連接關閉
            con.Close();

同上

            string str = "Data Source=.;Initial Catalog=MySchool;uid=sa;";
            SqlConnection con = new SqlConnection(str);
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = "usp_selectInfo";
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter pare = new SqlParameter("@sex", "1");
            cmd.Parameters.Add(pare);
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds, "Info");
            dgvList.DataSource = ds.Tables["Info"];
            con.Close();

 三: C#調用帶輸出和返回值的存儲過程

在boy's number 的輸出:5 在返回值:100 在  學生框中支持模糊查詢 在dgvList控件輸出查詢的結果

數據庫--->可編程性--->存儲過程--->

create procedure usp_selectInfoOutput
@sex nvarchar(32),
@count int output
as
select * from Student where gender=@sex
select @count=count(1) from student
where gender=@sex
return 100

在<調用帶輸出和返回值的存儲過程>窗體里寫

 //1.1  連接字符串
            string str = "data source=.;initial catalog=MySchool;uid=sa;";
            //1.2 創建連接對象    呵呵
            SqlConnection con = new SqlConnection(str);
            SqlCommand cmd = con.CreateCommand();

            cmd.CommandText = "usp_selectInfoOutput";
            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter[] paras =
            {
                new SqlParameter("@sex","1"),
                //憑什么    C#  @count  輸出參數
                new SqlParameter("@count",SqlDbType.Int), 
                new SqlParameter("@myreturn",SqlDbType.Int) 
                //返回值
            };

            //為參數指定方向
            paras[1].Direction = ParameterDirection.Output;
            paras[2].Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.AddRange(paras);
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds, "StuInfo");

            dataGridView1.DataSource = ds.Tables["StuInfo"];
            //填充總人數
            txtNum.Text = paras[1].Value.ToString();
            txtReturn.Text = paras[2].Value.ToString();

四:模糊查詢  在Select控件中寫

string name = '%' + "hhe" + '%';
            //1.1  連接字符串
            string str = "data source=.;initial catalog=MySchool;uid=sa;";
            //1.2 創建連接對象    呵呵
            SqlConnection con = new SqlConnection(str);
            SqlCommand cmd = con.CreateCommand();
            //1.3  SQL腳本       like后直接跟@name
            //cmd.CommandText = "select * from student where studentname like @name";
            //cmd.CommandType = CommandType.Text;
            //SqlParameter para = new SqlParameter("@name", '%' + txtName.Text + '%');
            //同下三行代碼效果一樣
            cmd.CommandText = "select * from student where studentname like '%'+@name+'%'";
            cmd.CommandType = CommandType.Text;
            SqlParameter para = new SqlParameter("@name",  txtName.Text);

            cmd.Parameters.Add(para);

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds, "StuInfo");
            dataGridView1.DataSource = ds.Tables["StuInfo"];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM