欢迎光临
我们一直在努力

使用OleDbCommand对象更新SQL Server中的二进制文件-.NET教程,面向对象编程

建站超值云服务器,限时71元/月

使用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 );

}

}

}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 使用OleDbCommand对象更新SQL Server中的二进制文件-.NET教程,面向对象编程
分享到: 更多 (0)

相关推荐

  • 暂无文章