The three will understand common sense

Preface:

Recently I knocked three of the code, because the code inside some small series ignorant, and therefore never knew him. Xiao Bian today summed up what these simple code, provided a good opportunity to review the old knowledge to everyone. If flawed, please treatise.

text:

using System.Data.SqlClient;//引用命名空间

Using System.Data.SqlClient  intended to reference the name of the System.Data.SqlClient namespace.

using an access defined in the C # language, will release the one or more objects outside of this range.

Namespace is used to organize and reuse code. Namespace is the name that uniquely identifies, in a different namespace, class name can be the same.

System.Data.SqlClient  contains many classes this namespace, in three layers, we will use the class are the following:

the SqlConnection ----------- represents a connection to SQL sever database

of the SqlCommand ------------ represents a Transact-SQL statement or stored procedure to execute against SQL sever database.

the SqlDataReader -------- shaped flow provides a read-only mode (which is the fastest way for reading data from the read-only database SQL sever Method ).

the SqlParameter ---------- represents a parameter, or a map with SqlCommand DataSet column.

namespace Login.DAL
{
    public class ScoreDAO
    {
        public void UpdateScore(string userName, int value)
        {
            using (SqlConnection conn = new SqlConnection(DbUtil.ConnString))
            {
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = @"INSERT INTO SCORES (UserName, Score) Values(@UserName,@Score)";
                cmd.Parameters.Add(new SqlParameter("@UserName", userName));
                cmd.Parameters.Add(new SqlParameter("@Score", value));

                conn.Open();
                cmd.ExecuteNonQuery();

            }
        }
    }
}

Anti SQL injection methods

Parameterized SQL refers to the time in the design and database links and access data, in place need to fill values ​​or data, use parameters (Parameter) to give value to represent the parameters with @.

In the case of a parameterized query, the database server will not be content as a parameter processing SQL commands, but only as a value for processing, so you can prevent SQL injection.

public void UpdateScore(string userName, int value)
            //写一个增加积分的方法,从B层获取数据
        {
            using (SqlConnection conn = new SqlConnection(DbUtil.ConnString))
            {
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = @"INSERT INTO SCORES (UserName, Score) Values(@UserName,@Score)";
                cmd.Parameters.Add(new SqlParameter("@UserName", userName));
                cmd.Parameters.Add(new SqlParameter("@Score", value));

                conn.Open();
                cmd.ExecuteNonQuery();

            }
        }

The role of "@" in

① ignore the escape character

eg:

//使用@前
string fileName = "D:\\文本文件\\text.txt";

//使用@后
string fileName = @"D:\文本文件\text.txt";

② let the string interbank

eg:

//使用@前
cmd.CommandText = "SELECT ID,UserName,Password,Email"
                  + "FROM USERS WHERE UserName=@UserName" 
                  + "AND Password=@Password"; 


//使用@后
cmd.CommandText = @"SELECT ID,UserName,Password,Email
                   FROM USERS WHERE UserName=@UserName
                   AND Password=@Password"; 

③ in identifiers

Variables can be defined by an @ before the keyword, this keyword may be used as identifiers (like variable names, method names, etc.).

 

Throw new exception exception handling

This is the three layers come without a sound pit ambush, after Qiaowan three, enter the correct account password ------ successful landing, there is no longer landed wrong password for the account to test, so as to cause error shown in FIG.

This error occurs because the throw keyword, this is mainly used for throwing an exception, it is required to use in the UI layer try ....... catch to receive the exception, otherwise it will error.

Therefore the code written as follows:

        private void BTLogin_Click(object sender, EventArgs e)
        {
            
            try
            //对try块代码进行异常捕捉,
            //如无异常则进行直try块结束,
            //如有异常则跳转进入catch块。
            {
                string userName = txtUserName.Text.Trim();
                string password = txtPassword.Text;
                Login.BLL.LoginManager mgr = new Login.BLL.LoginManager();
                //将用户输入的数据传给BLL,在下面一句的使用中,就直接从BLL调用数据
                Login.Model.UserInfo user = mgr.UserLogin(userName, password);
                //在这里就可以返回model里的userinfo
                MessageBox.Show("登陆用户:" + user.UserName);
            }

            catch (Exception ex)
            //处理异常。如下进行处理
            {
                MessageBox.Show(ex.Message);
            }
        }

 

Published 64 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/YaraRen/article/details/103252031