webForumDet fria alternativet

Hämta binära data från databas

.NET

2 svar · 342 visningar · startad av devotion

Medlem sedan jan. 20013 582 inlägg
Frågan#1

Hej,

Jag vill hämta binära data från ett BLOG-fält i en databas och skriva filen till en mapp.

Jag hittade denna koden:

<%#

    Set rs = Script.CreateObject("adodb.recordset")
    strSQL = "select logo, pub_id from pub_info"
    rs.Open strSQL, "Provider=SQLOLEDB;Initial Catalog = pubs;UserID=sa"

    Do While Not rs.EOF
          Output.Filename = CStr(rs("pub_id")) & ".gif"
          Output.BinaryWrite rs("logo")
          Output.Close
          
          rs.MoveNext
    Loop
     
    rs.Close
    Set rs = Nothing

#%>

Kan man göra något liknande för vbScript.

Mvh
Henrik

Medlem sedan jan. 20013 582 inlägg
#2

Hej igen! :)

Efter lite letande på nätet har jag fått till nedanstående kod:


	dim Rs, Conn, sSQL, Stream
	dim Fs, File
	
	'Öppna databasen
	Set Conn=CreateObject("ADODB.Connection")
	Conn.Open "Provider=sqloledb;Data Source=KARLSKRONA\SQLExpress;Initial Catalog=UN;User id=sa;Password=xxx;"
	
	Set Rs=CreateObject("ADODB.Recordset")
	Set Stream=CreateObject("ADODB.Stream")
	
	sSQL = "SELECT [Id], BinDocType, BinData FROM tblDocument Where ID IN (10002)"
	Rs.Open sSQL, Conn

	Do While Not Rs.EOF
		Stream.open
		Stream.type = 1
		Stream.Write Rs.Fields("BinData").Value
		Stream.SaveToFile "C:\" & CStr(Rs("Id")) & "." & Rs("BinDocType"), 1
		Stream.Close
		Rs.MoveNext
	Loop

	Set Stream=Nothing
	Rs.Close
	Set Rs = Nothing
	Set Conn = Nothing

Den fungerar och min fil skrivs till disk.

Men, är det rätt? Kan man optimera något, är det något jag glömt?

Mvh
Henrik

Medlem sedan jan. 20013 582 inlägg
#3

Hej!

Nu ser funktionen ut så här:

unction GetDocument(lDocId)

	dim Rs, Conn, Stream
	dim sSQL
	dim sOutputPath, sFileName

	sOutputPath=application.setting("CommonPath") & "PdfOutput\"
	
	If not isnumeric(lDocId) then exit function

	'Öppna databasen
	Set Conn=CreateObject("ADODB.Connection")
	Conn.Open Application.sDbConnectionString
	
	Set Rs=CreateObject("ADODB.Recordset")
	Set Stream=CreateObject("ADODB.Stream")

	sSQL = "SELECT d.[BinDocType] AS DocType, d.[BinData] AS DocData, d.[Name] AS DocName" _
		& " FROM tblDocument d" _
		& " WHERE d.[Id] = " & lDocId & "" _
		& " AND d.BinDocType <> ''"

	Rs.Open sSQL, Conn

	if Rs.EOF then
		GetDocument=""
	else
		sFileName=CStr(lDocId) & "_" & Rs("DocName") & "." & Rs("DocType")
		
		Stream.open
		Stream.type = 1
		Stream.Write Rs("DocData")
		Stream.SaveToFile sOutputPath & sFileName, 1
		Stream.Close
		GetDocument=sOutputPath & sFileName
	end If

	Set Stream=Nothing
	Rs.Close
	Set Rs = Nothing
	Set Conn = Nothing

End function

Är det ok, eller ser ni något galet?

Mvh
Henrik

:)

259 ms totalt · 4 externa anrop · v20260731065814-full.86ec41c2
133 ms — deklarationer (db)
0 ms — hämta statistik (cache)
123 ms — hämta tråd, inlägg och bilagor (db)
122 ms — ändringar (db)