How to get image from SQL Server - image

I have table called IMG and there are columns ID and Content that holds pictures.
How is it possible to get picture from there?
I googled for this problem and what all I got was vb.net, c# and php - mysql.
Maybe someone can say what is the best and easiest way to get picture (sample, copy/paste code, program)?
Thank you!

try something like this (from d_r_w's answer):
SqlDataAdapter dataAdapter = new SqlDataAdapter(
new SqlCommand("SELECT pic FROM imageTest WHERE pic_id = 1",
yourConnectionReference));
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count == 1)
{
Byte[] data = new Byte[0];
data = (Byte[])(dataSet.Tables[0].Rows[0]["pic"]);
MemoryStream mem = new MemoryStream(data);
yourPictureBox.Image= Image.FromStream(mem);
}
Take alook at the complete answer
More options to do this:
Uploading / Downloading Pictures to / from a SQL Server
http://www.sqlusa.com/bestpractices/imageimportexport/
I found this post regards PHP but with MySQL(you need to change the connection to your server):
<?php
// image.php - by Hermawan Haryanto <hermawan#dmonster.com>
// Example PHP Script, demonstrating Storing Image in Database
// Detailed Information can be found at http://www.codewalkers.com
// database connection
$conn = mysql_connect("localhost", "user", "password")
OR DIE (mysql_error());
#mysql_select_db ("hermawan", $conn) OR DIE (mysql_error());
$sql = "SELECT * FROM image WHERE image_id=".$_GET["iid"];
$result = mysql_query ($sql, $conn);
if (mysql_num_rows ($result)>0) {
$row = #mysql_fetch_array ($result);
$image_type = $row["image_type"];
$image = $row["image"];
Header ("Content-type: $image_type");
print $image;
}
?>

after a lot of reading and work found the solution!
Here it is! Works 100%
Dim conn, sql, a, filename
Dim dir
dir = "c:\images\" //saves files into this directory
Dim fileObj
Set fileObj = CreateObject("Scripting.FileSystemObject")
Set conn = CreateObject("ADODB.Connection")
Dim strStream
Set strStream = CreateObject("ADODB.Stream")
Dim rstRecordset
Set rstRecordset = CreateObject("ADODB.Recordset")
conn.Open "Provider=SQLOLEDB;Data Source=yourserver;Integrated Security = SSPI","username","password"
rstRecordset.Open "Select xxx, yyy, zzz from table (nolock) where xxx = '' order by xxx desc", conn ', adOpenKeyset, adLockOptimistic
Set fso = CreateObject("Scripting.FileSystemObject")
While Not rstRecordset.EOF
filename = rstRecordset.Fields(0)
er = 0
Do
er = er+1
Loop While (fso.FileExists(dir & filename & "_" & er & ".JPG"))
filename = dir & filename & "_" & er & ".JPG"
strStream.Type = 1
strStream.Open
strStream.Write rstRecordset.Fields(2).Value
strStream.SaveToFile filename
strStream.Close
rstRecordset.MoveNext
Wend
Here it is!

Related

system.rank, system.keywords from SystemIndex

Looking to fetch some nice results working with Microsoft Search.
Got some problems...
First system.rank returns allways 1000.
I tried system.HitCount, it returns allways 65535.
Then I'm trying to match a word in the Keywords using System.Keywords...
The results of the request looks allways empty on Keywords?
strQuery = "SELECT SYSTEM.FILENAME, System.Keywords FROM SYSTEMINDEX WHERE scope= '" & scope & "' AND SYSTEM.FILENAME NOT LIKE '%.tmp' AND SYSTEM.FILENAME NOT LIKE '~$%' "
Dim constring As String = "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';"
Using con As New OleDbConnection(constring)
con.Open()
Dim da As New OleDbDataAdapter(strQuery, con)
Dim table AS new DataTable()
Dim ds As New DataSet()
Dim dc AS New DataColumn()
Dim cmdSearch As New System.Data.OleDb.OleDbCommand(strQuery, con)
Dim reader As OleDbDataReader = cmdSearch.ExecuteReader()
Dim result As New ArrayList()
table.Columns.Add("filename")
table.Columns.Add("DocKeywords")
If reader.HasRows Then
Do While reader.Read()
Dim row As Datarow = table.NewRow()
row("filename") = reader.Item("system.filename")
row("DocKeywords") = reader.Item("System.Keywords") 'String.Join(",", reader.Item("System.Keywords")) 'system.string[]: empty
table.Rows.Add(row)
Loop
End If
DataGrid1.DataSource = table
DataGrid1.DataBind()

Saving and Reading Images in Oracle with classic asp

i am utilizing aspSmartUpload to upload an image into an Oracle BLOB field, see below:
Set mySmartUpload = Server.CreateObject("aspSmartUpload.SmartUpload")
'*** Upload Files ***'
mySmartUpload.Upload
set file = mySmartUpload.Files("file1")
Set MyConn = Server.CreateObject("ADODB.Connection")
Call OpenConnect(MyConn)
sql = "SELECT attach_data, title, idx, attach_type_id FROM c_attachment"
Set Rs = Server.CreateObject("ADODB.recordset")
Set rs.ActiveConnection = MyConn
rs.Source = sql
rs.CursorLocation = 3
rs.CursorType = 0
rs.LockType = 3
rs.Open sql
If not file.IsMissing Then 'Check for missing file
'Add the current file in database
Rs.AddNew
file.FileToField Rs.Fields("attach_data")
Rs("title") = "title test"
rs("idx") = "134774"
rs("attach_type_id") = 1
Rs.Update
rs.Close
set rs = nothing
End If
when i check the db table. attach_data is populated. now. when i try to read the image back, i keep getting "Response object: 007~ASP 0106~Type Mismatch~An unhandled data type was encountered." error on the BinaryWrite. please help!
Set MyConn = Server.CreateObject("ADODB.Connection")
Call OpenConnect(MyConn)
SQLQuery = "select attach_data,title from c_attachment where attach_id = 109"
Set RSList = MyConn.Execute(SQLQuery)
If RSList.EOF Then
blnImgExists = False
Else
FileData = RSList("attach_data")
blnImgExists = true
End If
if blnImgExists Then
Response.Clear
Response.ContentType = "image/jpeg"
Response.AddHeader "Content-disposition", "attachment; filename=image.jpg"
Response.BinaryWrite RSList("attach_data")
else
response.write "count not open"
end if
Images should be stored as BLOB data (Binary Large Object) in Oracle, not CLOB (Character Large Object).

VBA Recordset / Oracle and Excel Connect

I've installed tries recordset in my vba statement.
Unfortunately he accesses only the first line in my database. Who can help me?
I'm not very good in VBA it's my first porject. I hope someone can help me with my code. Thank you
Sub Testbox()
Dim conn, Rs
Dim strSQL As String
Dim auswahl As Integer
auswahl = MsgBox("Die Daten werden geladen", vbOKCancel, "Bitte auswählen")
If auswahl = 1 Then
connstring = "UID=user;PWD=passwort;DRIVER={Microsoft ODBC For Oracle};SERVER=server.WORLD;"
Set conn = New ADODB.Connection
With conn
.ConnectionString = connstring
.CursorLocation = adUseClient
.Mode = adModeRead
.Open
End With
Set Rs = CreateObject("ADODB.Recordset")
strSQL = "select * from table where logdatum =1507"
Rs.Open strSQL, conn, 3, 3
Range("A2:A5000") = Rs("scanclient")
Range("B2:B500") = Rs("Sum")
Range("C2:C500") = Rs("batchclass")
Rs.Close
Set Rs = Nothing
conn.Close
Set conn = Nothing
Else
Exit Sub
End If
End Sub
Unfortunately, it is not possible to print data from Recordset into worksheet like that:
Range("A2:A5000") = Rs("scanclient")
Range("B2:B500") = Rs("Sum")
Range("C2:C500") = Rs("batchclass")
You need to replace this code with the below:
Dim i As Long: i = 1
Do Until Rs.EOF
i = i + 1
Cells(i, 1) = Rs("scanclient")
Cells(i, 2) = Rs("Sum")
Cells(i, 3) = Rs("batchclass")
Call Rs.MoveNext
Loop

How to use DataReader from Oledb and get results in Richtextbox

Dim srch As String
srch = ccode.Text
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + IO.Directory.GetCurrentDirectory + "\ptdr.accdb"
cmd.Connection = conn
conn.Open()
Dim dsrch As New OleDbCommand("SELECT pname, page, vdate, psex, summer, bldp, blds, photh, diag, rl, trtmnt, nvdate FROM ptnt_data WHERE pcode = " & srch & "", conn)
Dim rdr As OleDbDataReader = dsrch.ExecuteReader()
Dim dg As String = ""
'diagnosis'
dg = rdr.GetString(8).ToString()
If String.IsNullOrEmpty(dg) Then
diag1.Text = ""
ElseIf String.IsNullOrWhiteSpace(dg) Then
diag1.Text = ""
Else
diag1.Text = dg
End If
It works fine but when I search for a null it gives an error.
It says that I've an error at the line of
dg = rdr.GetString(8).Tostring()
any suggests?
rdr.GetString(8).ToString()
if rdr.GetString(8) is null this is a classic null reference exception
rdr.GetString(8) IS a string so just remove the .ToString()
As per my comment below you can only run GetString if the DB has an underlying type of string for this data, what is the datatype of column diag?
(ie run rdr.GetFieldType(8) in the debugger and provide the type name)
As you have confirmed this is a string type and the issue is just with null handling (sorry i didn;t spot that from your question) you need:
If rdr.IsDBNull(8) Then diag1.Text = "" Else diag1.Text = rdr.GetString(8) EndIf
Which should replace everything from Dim dg... down

How to add picture into database?

I have created a table mypics that contains one column of BLOB datatype.
Now I need to implement a vb6 code to Select/Insert/Update data in this table, but I don`t know how to deal with the BLOB column...
SQL> desc mypics
Name Null? Type
PID NOT NULL NUMBER(38)
PNAME CHAR(10)
IMAGE BLOB
Please help
Here is some example code to get you started. Assume a table named tblImages with 3 fields.
Field Data Type Size
Picture Image
ID Int 4
To add an image from a file on disk to the database
Set strStream = New ADODB.Stream
strStream.Type = adTypeBinary
strStream.Open
strStream.LoadFromFile strFileName
strSQL = "SELECT ID, Picture FROM tblImages"
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Source = strSQL
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With
rs.AddNew
rs.Fields("ID").Value = ID
rs.Fields("Picture").Value = strStream.Read
rs.Update
rs.Close
Set rs = Nothing
To extract the file from database to a disk file :
strSQL = "SELECT Picture FROM tblImages WHERE ID = " & ID
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Source = strSQL
.Open
End With
If Not (rs.BOF And rs.EOF) Then
Set strStream = New ADODB.Stream
strStream.Type = adTypeBinary
strStream.Open
strStream.Write rs!Picture
strStream.SaveToFile TempPath, adSaveCreateOverWrite
strStream.Close
Set strStream = Nothing
End If
rs.Close
Set rs = Nothing
I hope this helps.

Resources