C#将本地目录中的图片以二进制插入到数据库中,大家看看代码哪里也错了,报错了。
目录中的图片:数据库中的字段://C#代码:usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;us...
目录中的图片:
数据库中的字段:
//C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string conn = "server=.;database=DaWu;Uid=sa;Pwd=521521 ";
using (SqlConnection myconn = new SqlConnection(conn))
{
myconn.Open();
using (SqlCommand mycomm = new SqlCommand())
{
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Administrator\Documents\Visual Studio 2008\Projects\DaWuAnswer\DaWuAnswer\images1");
foreach (FileInfo item in dir.GetFiles("*.jpg"))
{
string fileName = item.Name.Replace(".jpg", "");
string para = string.Format("{0}",fileName);
string str = string.Format("insert into [WordAnswer] (words,imagAns) values('{0}',{1})", fileName, para);
mycomm.CommandText = str;
mycomm.Connection = myconn;
FileStream fs = new FileStream(item.FullName, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
Byte[] byData = br.ReadBytes((int)fs.Length);
fs.Close();
mycomm.Parameters.Add(para, SqlDbType.Binary, byData.Length);
mycomm.Parameters[para].Value = byData;
mycomm.ExecuteNonQuery();
}
}
}
}
}
} 展开
数据库中的字段:
//C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string conn = "server=.;database=DaWu;Uid=sa;Pwd=521521 ";
using (SqlConnection myconn = new SqlConnection(conn))
{
myconn.Open();
using (SqlCommand mycomm = new SqlCommand())
{
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Administrator\Documents\Visual Studio 2008\Projects\DaWuAnswer\DaWuAnswer\images1");
foreach (FileInfo item in dir.GetFiles("*.jpg"))
{
string fileName = item.Name.Replace(".jpg", "");
string para = string.Format("{0}",fileName);
string str = string.Format("insert into [WordAnswer] (words,imagAns) values('{0}',{1})", fileName, para);
mycomm.CommandText = str;
mycomm.Connection = myconn;
FileStream fs = new FileStream(item.FullName, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
Byte[] byData = br.ReadBytes((int)fs.Length);
fs.Close();
mycomm.Parameters.Add(para, SqlDbType.Binary, byData.Length);
mycomm.Parameters[para].Value = byData;
mycomm.ExecuteNonQuery();
}
}
}
}
}
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询