SqlParameter的作用与用法
一般来说,在更新DataTable或是DataSet时,如果不采用sqlParameter,那么当输入的sql语句出现歧义时,如字符串中含有单引号,程序就会发生错误,并且他人可以轻易地通过拼接sql语句来进行注入攻击。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
上述代码未采用sqlParameter,除了存在安全性问题,该方法还无法解决二进制流的更新,如图片文件。通过使用sqlParameter可以解决上述问题,常见的使用方法有两种,Add方法和AddRange方法。
一、Add方法
该方法每次只能添加一个sqlParameter。上述代码的功能是将ID值等于1的字段name更新为Pudding(人名)。
二、AddRange方法
public
int
SavePhoto(
photourl)
{
FileStream fs =
FileStream(photourl,FileMode.Open,FileAccess.Read);
//创建FileStream对象,用于向BinaryReader写入字节数据流
BinaryReader br =
BinaryReader(fs);
//创建BinaryReader对象,用于写入下面的byte数组
byte
[] photo = br.ReadBytes((
int
)fs.Length);
//新建byte数组,写入br中的数据
br.Close();
//记得要关闭br
fs.Close();
//还有fs
"update Table1 set photo = @photo where ID = '0'"
;
sqlConnection();
;
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.8em!important; outline:0px!important; overflow:visible!important; padding:0px 1em!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; min-height:inherit!important; white-space:Nowrap!important; background:none rgb(244,conn);
"@photo"
404@cmd.Parameters.Add(sp);
try
{
conn.open();
(cmd.ExecuteNonQuery());
}
(Exception)
{
-1;
;
}
finally
{
conn.Close();
}
}
void
ReadPhoto(
url)
{
"select photo from Table1 where ID = '0'"
;
sqlConnection();
;
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.8em!important; outline:0px!important; overflow:visible!important; padding:0px 1em!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; min-height:inherit!important; white-space:Nowrap!important; background:none rgb(244,conn);
try
{
conn.open();
if
(reader.Read())
{
[] photo = reader[0]
as
[];
//将第0列的数据写入byte数组
FileStream(url,FileMode.CreateNew);创建FileStream对象,用于写入字节数据流
fs.Write(photo,photo.Length);
//将byte数组中的数据写入fs
//关闭fs
}
reader.Close();
//关闭reader
}
(Exception ex)
{
;
}
finally
{
conn.Close();
}
}
}
|
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。