2024年2月21日发(作者:)

一般来说,在更新DataTable或是DataSet时,如果不采用SqlParameter,那么当输入的Sql语句出现歧义时,如字符串中含有单引号,程序就会发生错误,并且他人可以轻易地通过拼接Sql语句来进行注入攻击。

SqlParameterCollection 仅接受非空的 SqlParameter 类型对象,不接受

SqlParameter[] 对象,主要是varchar类型的字段,如果使用默认长度,但默认长度大于表中字段长度或者默认长度小于赋值变量的长度,都会截断那些多余的字符的。

string sql = "update Table1 set name = 'Pudding' where ID = '1'";//未采用SqlParameter

SqlConnection conn = new SqlConnection();

tionString = "server=.;database=studentmanagement;uid=admin;pwd=admin123";//连接字符串与数据库有关

SqlCommand cmd = new SqlCommand(sql, conn);

try

{ ();

return(eNonQuery());

}

catch (Exception)

{

return -1;

throw;

}

finally

{

();

}

上述代码未采用SqlParameter,除了存在安全性问题,该方法还无法解决二进制流的更新,如图片文件。通过使用SqlParameter可以解决上述问题,常见的使用方法有两种,Add方法和AddRange方法。

一、Add方法

SqlParameter sp = new SqlParameter("@name", "Pudding");

(sp);

sp = new SqlParameter("@ID", "1");

(sp);

该方法每次只能添加一个SqlParameter。上述代码的功能是将ID值等于1的字段name更新为Pudding(人名)。

二、AddRange方法

SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@name", "Pudding"), new SqlParameter("@ID", "1") };

ge(paras);

显然,Add方法在添加多个SqlParameter时不方便,此时,可以采用AddRange方法。

下面是通过SqlParameter向数据库存储及读取图片的代码。

public int SavePhoto(string photourl)

{

FileStream fs = new FileStream(photourl, , );//创建FileStream对象,用于向BinaryReader写入字节数据流

BinaryReader br = new BinaryReader(fs);//创建BinaryReader对象,用于写入下面的byte数组

byte[] photo = tes((int)); //新建byte数组,写入br中的数据

();//记得要关闭br

();//还有fs

string sql = "update Table1 set photo = @photo where ID = '0'";

SqlConnection conn = new SqlConnection();

tionString = "Data Source=.SQLExpress;Integrated Security=true;AttachDbFilename=|DataDirectory|;User Instance=true";

SqlCommand cmd = new SqlCommand(sql, conn);

SqlParameter sp = new SqlParameter("@photo", photo);

(sp);

try

{

();

return (eNonQuery());

}

catch (Exception)

{

return -1;

throw;

}

finally

{

();

}

}

public void ReadPhoto(string url)

{

string sql = "select photo from Table1 where ID = '0'";

SqlConnection conn = new SqlConnection();

tionString = "Data Source=.SQLExpress;Integrated Security=true;AttachDbFilename=|DataDirectory|;User Instance=true";

SqlCommand cmd = new SqlCommand(sql, conn);

try

{

();

SqlDataReader reader = eReader();//采用SqlDataReader的方法来读取数据

if (())

{

byte[] photo = reader[0] as byte[];//将第0列的数据写入byte数组

FileStream fs = new FileStream(url,New);创建FileStream对象,用于写入字节数据流

(photo,0,);//将byte数组中的数据写入fs

();//关闭fs

}

();//关闭reader

}

catch (Exception ex)

{

throw;

}

finally

{

();

}

}

}