六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 186|回复: 0

插入图片文件到MySql和MSSql数据库

[复制链接]

升级  18.67%

22

主题

22

主题

22

主题

秀才

Rank: 2

积分
78
 楼主| 发表于 2012-12-29 11:10:25 | 显示全部楼层 |阅读模式
<div id="cnblogs_post_body">使用C#将指定文件夹以及子文件夹中的图片文件插入到MSSql数据库:
<div class="cnblogs_code">using System.Data.SqlClient;using System;using System.IO;public class Photo{    public static void Main(string[]args)    {        byte[]byts=null;        FileStream fs=null;        string []files=Directory.GetFiles("./images","*.*",SearchOption.AllDirectories);        string connstr="data source=localhost;initial catalog=test;user id=sa;password=sa1234;";        SqlConnection connection=new SqlConnection(connstr);        connection.Open();        foreach(string file in files)        {            string ext=Path.GetExtension(file);            string name=Path.GetFileNameWithoutExtension(file);            fs=new FileStream(file,FileMode.Open);            int size=(int)fs.Length;            byts=new byte[size];            fs.Read(byts,0,size);            SqlCommand command=connection.CreateCommand();            command.CommandText="select count(*) from photo where name='"+name+"'";            if(Convert.ToInt32(command.ExecuteScalar())==0)            {                command.CommandText="insert into Photo(photo,name,size,extension) values(@photo,@name,@size,@extension)";                command.Parameters.Add(new SqlParameter("photo",byts));                command.Parameters.Add(new SqlParameter("name",name));                command.Parameters.Add(new SqlParameter("size",size));                command.Parameters.Add(new SqlParameter("extension",ext));                int effect=command.ExecuteNonQuery();                if(effect>0)                {                    Console.WriteLine(file+"插入成功!");                }                else                {                    Console.WriteLine(file+"插入失败!");                }            }        }        connection.Close();        fs.Close();    }}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表