c# mysql 文件存储_C# 文件在数据库 的 存取

这篇博客介绍了如何使用C#连接MySQL数据库,实现文件的存储和读取。通过按钮事件,用户可以将文件内容转化为byte数组存入数据库,或者从数据库中读取Image字段的数据并保存到本地。具体实现包括对数据库的连接、SQL命令的执行以及文件流的处理。
摘要由CSDN通过智能技术生成

///

///获取数据库Image字段数据,保存到本地///

///

///

private void button2_Click(objectsender, EventArgs e)

{string constr = "Data Source=IP地址服务器地址;Initial Catalog=SunS;User ID=sa;Password=1321654";

SqlConnection con= newSqlConnection(constr);

SqlCommand cmd= newSqlCommand();

cmd.CommandText= "Select * from FileServer With (NoLock) Where FileName = '" + textBox1.Text + "'";

cmd.CommandType=CommandType.Text;

cmd.Connection=con;

con.Open();

DataTable dt= newDataTable();

SqlDataAdapter ad= new SqlDataAdapter(cmd);//cmd.EndExecuteReader();

ad.Fill(dt);

con.Close();

cmd.Dispose();byte[] pics1 = (byte[])dt.Rows[0]["CONTENT"];//的值强制转换;

writefile(pics1, "D://" + textBox1.Text + "");

}public void writefile(byte[] pics, stringfilename)

{

FileStream fs= newFileStream(filename, FileMode.Append, FileAccess.Write);

BinaryWriter bw= newBinaryWriter(fs);

bw.Write(pics,0, pics.Length);

bw.Close();

fs.Close();

}///

///将文件转换成byte数组,写入数据库///

///

///

private void button1_Click(objectsender, EventArgs e)

{

FileInfo finfo= new FileInfo("D://" + textBox1.Text); //绝对路径

if(finfo.Exists)

{

SqlConnection conn= new SqlConnection( "Data Source=IP地址服务器地址;Initial Catalog=Sun;User ID=sa;Password=1312313");

SqlCommand InsertCommand= newSqlCommand();

InsertCommand.Connection=conn;

InsertCommand.CommandText= "UPDATE FileServer SET CONTENT =@Content WHERE [FILENAME] = '" + textBox1.Text + "'";

InsertCommand.Parameters.Add("@Content", SqlDbType.Image, (int)finfo.Length, "CONTENT"); //注意,此处参数Size为写入的字节数//读取文件内容,写入byte数组

byte[] content = new byte[finfo.Length];

FileStream stream=finfo.OpenRead();

stream.Read(content,0, content.Length);

stream.Close();

InsertCommand.Parameters["@Content"].Value = content; //为参数赋值

try{

conn.Open();

InsertCommand.ExecuteNonQuery();

}finally{

conn.Close();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值