当前位置:网站首页>Executing SQL statements with parameterized commands
Executing SQL statements with parameterized commands
2022-06-24 18:39:00 【MousseIn】
Parameterized command execution sql sentence
Understand the benefits of parameterized instructions
- prevent sql Inject
string sb = “SELECT *FROM admin WHERE loginid =’”+loginId+"‘AND loginPwd =’"+logingPwd+"’"
string sb =“SELECT * FROM admin WHERE loginid =” or 1=1 --AND loginPwd = ‘xxx’
Use this splicing method , Two disadvantages :
- Not beautiful , And it's easy to make mistakes .
- Poor safety , Easy to be sql Injection attack .
Examples are as follows :
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CH03
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" Please enter a user name :");
string name = Console.ReadLine();
Console.WriteLine(" Please input a password :");
string pwd = Console.ReadLine();
int count = 0;
string conStr = "data source=(local);database=MySchool;uid=sa;pwd=123456";
using (SqlConnection con = new SqlConnection(conStr))
{
con.Open();
string sql = "select count(*) from dbo.student where studentno = "+ name +" and loginpwd = '"+pwd +"'";
SqlCommand cmd = new SqlCommand(sql,con);
count = Convert.ToInt32(cmd.ExecuteScalar());
}
if (count > 0)
{
Console.WriteLine(" Landing successful !");
}
else
{
Console.WriteLine(" Login failed !");
}
Console.ReadKey();
}
}
}
I use count This parameter is used to receive the number of affected rows returned , If the number of returned rows is greater than zero , Login succeeded , If the number of returned rows is less than zero , Login failed .
If we enter... In the user name column "3 or 1=1 --" The original statement to go to the database
select count(*) from dbo.student where studentno = '23214' and loginpwd = '0000'
Turned into
select count(*) from dbo.student where studentno = 3 or 1 = 1 -- and loginpwd = '123456'
Heng holds and the database password is commented out .
Execution results count The return value is fixed to have a value , Therefore, the login is successful .
Parameterized query is an implementation that can effectively avoid the above drawbacks sql How statements work .
Master the use of parameterized instructions to execute sql sentence
Use @ Construct parameterization sql command
sqlParameter object
- and “@” The decorated parameters correspond to each other , To replace this parameter
adopt Commend Of Parameters Attribute addition SqlParameter object
SqlParameter Properties of
- DbType The data type of the corresponding database
- Direction Parameters can only be entered 、 No output 、 Bidirectional or stored procedure return value parameter
- IsNullable Whether the parameter accepts null values
- ParameterName Name of parameter
- Size The maximum size of the data corresponding to the parameter
- SqlDbType SQL Server The data type of the database
- Value The value of the parameter
Use SqlCommmand Perform parameterization SQL Steps for
- Construct database link objects
- Construct parameterization SQL sentence
- structure SqlParameter object
- establish SqlCommand object , Use SqlParameter Object fill data
- Open database link , perform SqlCommand command
Examples are as follows :
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CH03
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" Please enter a user name :");
string name = Console.ReadLine();
Console.WriteLine(" Please input a password :");
string pwd = Console.ReadLine();
int count = 0;
string conStr = "data source=(local);database=MySchool;uid=sa;pwd=123456";
using (SqlConnection con = new SqlConnection(conStr))
{
con.Open();
// Build parameterization sql sentence
string sql = "select count(*) from student where studentno [email protected] and loginpwd = @pwd";
// Build the value to replace , structure sqlparameter object
SqlParameter[] par = {
new SqlParameter("@n",name),// relation
new SqlParameter("@pwd",pwd)
};
//string sql = "select count(*) from dbo.student where studentno = "+ name +" and loginpwd = '"+pwd +"'";
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.AddRange(par);// Add a parameterized array to cmd in
count = Convert.ToInt32(cmd.ExecuteScalar());
}
if (count > 0)
{
Console.WriteLine(" Landing successful !");
}
else
{
Console.WriteLine(" Login failed !");
}
Console.ReadKey();
}
}
}
Input again sql Injection method :
Incoming sql Statement for :
select count(*) from student where studentno [email protected] and loginpwd = @pwd
Rather than using + No sql sentence .
The advantage is that :
- High safety , Effectively avoid SQL Inject
- The code is simple and beautiful
边栏推荐
- Five advantages and disadvantages of Bi
- Microservice system design -- interface document management design
- SAP license: ERP for supply chain management and Implementation
- 如何在 R 中使用 Fisher 的最小显着性差异 (LSD)
- Graph traversal (BFS and DFS) C language pure handwriting
- 中电投先融期货这家公司怎么样?期货开户办理安全吗?
- SDL: cannot play audio after upgrading openaudio to openaudiodevice
- Seven strategies for successfully integrating digital transformation
- ASP. Net hosting uploading file message 500 error in IIS
- Common MySQL commands of installation free version
猜你喜欢

JS position operation

JS event details

Wechat applet to realize stacked rotation
What if the database table structure changes? Smartbi products support one click synchronization

Graph traversal (BFS and DFS) C language pure handwriting

Nacos cluster starts throwing set of SQL_ SELECT_ LIMIT is not support

How can an enterprise successfully complete cloud migration?

Three indicators to help you measure the effectiveness of digital transformation

解决执行MapReduce程序控制台没有日志信息WARN Please initialize the log4j system properly

JS string method
随机推荐
Is there a security risk in opening an account online? What to do if the business department opening an account nearby is far away from home. Is there any capital requirement for opening an account?
About whether arm's large and small end mode is related to CPU or compiler
Mariana Trench, Facebook's open source code analysis tool
Leetcode topic [array] -216- combined sum III
Three indicators to help you measure the effectiveness of digital transformation
What is decision intelligence?
Solve the problem that the MapReduce program console does not have log information warn please initialize the log4j system properly
Two micro service interviews where small companies suffer losses
Exception: Gradle task assembleDebug failed with exit code 1
congratulate! The first dragon lizard community annual outstanding contribution award is announced. Check it now
How to select the best test cases for automation?
Data driven decision making: Decision intelligence and design thinking
微服务系统设计——接口文档管理设计
Tencent cloud won the "trusted cloud technology best practice - virtualization"
Millions of dollars worth of NFT were stolen in the attack, and Google issued an emergency warning to 3.2 billion users worldwide | February 21 global network security hotspot
The mixed calculation of rpx and PX in JS by the uniapp applet
Skills of writing test cases efficiently
Paper sharing | self supervised learning paper jointly released by Yann Lecun and read by engineers
Location object
Easyplayer streaming media player plays HLS video. Technical optimization of slow starting speed