使用oledbcommand对象更新sql server中的二进制文件
作者 朱二
利用ado.net中的oledbconnection\oledbcommand 可以方便的对sql server中的二进制文件进行更新操作,下面是详细的代码演示
演示环境:
数据库机器名 :s_test
登陆名 :sa
密码 :7890
数据库名 db_test
下面建立一个表:
create table tb_test(id int identity(1,1),photo image ,constraint pk_tb_test primary key(id))
一、将硬盘上的文件保存至数据库(c#)
//———————————————————-
//———————————————————-
//下面的示例将c:\1.txt文件保存至数据库的tb_test表中
//———————————————————-
//———————————————————-
using system;
using system.io;?
using system.data;
using system.data.oledb;
class image_test
{
[stathread]
static void main(string[] args)
{
try
{
//初始化oledbconnection和oledbcommand
oledbconnection cn = new oledbconnection("provider=sqloledb;server=s_test;user id=sa;password=7890;initial catalog=db_test");
oledbcommand cmd = new oledbcommand("insert tb_test(photo) values(?)",cn);
//打开文件
filestream fs = new filestream("c:\\1.txt", filemode.open, fileaccess.read);
byte[] b = new byte[fs.length];
fs.read(b, 0, b.length);
fs.close();
//打开连接
oledbparameter prm = new oledbparameter("@photo",oledbtype.varbinary ,b.length,?
parameterdirection.input, false, 0, 0, null,datarowversion.current, b);
cmd.parameters.add(prm);
cn.open();
//执行
if (cmd.executenonquery() == 1)
console.writeline("ok");
else
console.writeline("fail");?
cn.close();
}
catch(exception ex)
{
console.writeline(ex.message );
}
}
}?
三、更新数据库中保存的文件
//———————————————————-
//———————————————————-
//下面的示例用将数据库的tb_test表中id=1的记录的photo更新为c:\1.txt
//———————————————————-
//———————————————————-
using system;
using system.io;?
using system.data;
using system.data.oledb;
class image_test
{
[stathread]
static void main(string[] args)
{
try
{
//初始化oledbconnection和oledbcommand
oledbconnection cn = new oledbconnection("provider=sqloledb;server=s_test;user id=sa;password=7890;initial catalog=db_test");
oledbcommand cmd = new oledbcommand("update tb_test set photo= ? where id=1",cn);
//打开文件
filestream fs = new filestream("c:\\1.txt", filemode.open, fileaccess.read);
byte[] b = new byte[fs.length];
fs.read(b, 0, b.length);
fs.close();
//打开连接
oledbparameter prm = new oledbparameter("@photo",oledbtype.varbinary ,b.length,?
parameterdirection.input, false, 0, 0, null,datarowversion.current, b);
cmd.parameters.add(prm);
cn.open();
//执行
if (cmd.executenonquery() == 1)
console.writeline("ok");
else
console.writeline("fail");?
cn.close();
}
catch(exception ex)
{
console.writeline(ex.message );
}
}
}
