且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在vb.net 2008中存储和检索(.doc / .docx / .pdf)文件到sql server数据库

更新时间:2023-01-30 17:18:02

要做的第一件事是更改保存数据的方式:insert语句有两个问题。

首先,您应该明确列出要保存数据的字段 - 匿名条目依赖于您的数据库将来不会更改。

The first thing to do is to change the way you are saving the data: there are two problems with your insert statement.
The first is that you should explicitly list the fields into which you want to save the data - anonymous entry relies on your DB not changing in the future.
sqltxt = "insert into test values('" & TextBox1.Text & "',@fdoc)"



成为:


Becomes:

sqltxt = "insert into test (fileName, fileData) values('" & TextBox1.Text & "',@fdoc)"





第二个是你真的应该使用你设置的参数化查询来指定文本 - 通过字符串连接传递TextBox内容是为了意外或故意的Sql注入攻击而打开您的数据库。您将文件数据作为参数传递,那么为什么不传递TextBox内容呢?



要检索它与您用于任何其他数据库的过程完全相同访问:



The second is that you really, really, should use the parametrized query you are setting up to specify the text as well - passing the TextBox content by string concatenation is opening your database up for an accidental or deliberate Sql Injection Attack. You are passing the file data as a parameter, so why not pass the TextBox content as well?

To retrieve it is exactly the same process you use for any other database access:

Using con As New SqlConnection(strConnect)
	con.Open()
	Using com As New SqlCommand("SELECT fileName, fileData FROM test", con)
		Using reader As SqlDataReader = com.ExecuteReader()
			While reader.Read()
				Dim fileName As String = DirectCast(reader("fileName"), String)
				Dim fileData As Byte() = DirectCast(reader("fileData"), Byte())
				...
			End While
		End Using
	End Using
End Using