[VB.NET]如何向数据库字段中写入文件?

前端之家收集整理的这篇文章主要介绍了[VB.NET]如何向数据库字段中写入文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何向数据库字段中写入文件? 1 如何向数据库字段中写入文件?(EXE,TXT,DOC等等) 2 如果文件较大,如何获取写入进度? 3 如何判断文件写入成功? __________________________________________________________________________ 忘了说了,还有就是如何读取这些文件 __________________________________________________________________________ 将文件流转化为二进制数据后写入数据库,下面是我写的代码用于读写图片文件的,你只需要在数据库中为字段选择varbinary类型就可以实现其他类型的存储了.没整理,有点乱. Dim b() As Byte Dim fs As filestream Dim br As BinaryReader Dim strsql As String Try fs = New FileStream(finfo.Name,FileMode.Open,FileAccess.Read) ''将选择的图像文件读入到文件流 br = New BinaryReader(fs) b = br.ReadBytes(fs.Length) ''将文件内容放到字节数组 Catch ex As Exception MsgBox( "在将文件读入内存时出错: " + ex.Message) End Try br.Close() fs.Close() strsql = "insert into test(imageName,photo) " strsql += "values( '' " & finfo.Name & " '',@photo) " ''二进制数据用@标识 Dim sqlCn As sqlConnection = New sqlConnection( "server=dell;database=study;uid=sa;pwd=; ") sqlCn.Open() Dim myCommand As sqlCommand = New sqlCommand(strsql,sqlCn) myCommand.Parameters.Clear() myCommand.Parameters.Add( "@photo ",OleDb.OleDbType.Binary) myCommand.Parameters( "@photo ").Value = b myCommand.ExecuteReader() 读取文件代码如下: Dim strsql As String strsql = "select * from test " Dim sqlCn As sqlConnection = New sqlConnection( "server=dell;database=study;uid=sa;pwd=; ") Dim bw As BinaryWriter Dim bufferSize As Integer = 100 ''定义缓冲区长度为100 Dim outbyte() As Byte = New Byte(bufferSize - 1) {} ''定义缓冲区 Dim retval As Long Dim startIndex As Long = 0 Dim dr As sqlDataReader Dim myCommand As sqlCommand = New sqlCommand(strsql,sqlCn) sqlCn.Open() Dim ms As New System.IO.MemoryStream ''定义内存流对象,将数据库中存储的图像数据先放到内存流中 Try bw = New BinaryWriter(ms) dr = myCommand.ExecuteReader() dr.Read() TextBox1.Text = dr.GetString(1) startIndex = 0 retval = dr.GetBytes(2,startIndex,outbyte,bufferSize) Do While retval = bufferSize ''循环读取余下的内容,每次读取buffersize个字节 bw.Write(outbyte) bw.Flush() ''清空缓冲区 startIndex += bufferSize ''移动位置指针 retval = dr.GetBytes(2,bufferSize) Loop Dim image As Image = image.FromStream(ms) Me.PictureBox1.Image = image ''利用内存流在pictureBox生成图像 bw.Write(outbyte,retval) ''写入最后一块数据 bw.Flush() bw.Close() ms.Close() dr.Close() Catch ex As Exception MsgBox(ex.Message) End Try __________________________________________________________________________ 那如果是其他类型的文件呢,就不能用pictureBox控件了,那如何读取呢? __________________________________________________________________________ // 读取 int colIndex = DataReader.GetOrdinal( "MyLargeObjectColumnName "); byte[] buffer = new byte[DataReader.GetBytes(colIndex,null,int.MaxValue)]; DataReader.GetBytes(colIndex,buffer,buffer.Length); // 处理 buffer __________________________________________________________________________ 反正读出来全是二进制的,怎么搞随便 __________________________________________________________________________ 原文链接:https://www.f2er.com/vb/263992.html

猜你在找的VB相关文章