I can look up ALL the records from images with a VBScript:
cn.Execute "SELECT * INTO [text;HDR=Yes;Database=" & exportDir & _
";CharacterSet=65001]." & exportFile & " FROM IMAGES"
This works perfectly. However, I want to narrow down that search from all the records to just the ones where column B (ProjectName) == "spoon"
Dim projName
projName = "spoon"
cn.Execute "SELECT * INTO [text;HDR=Yes;Database=" & exportDir & _
";CharacterSet=65001]." & exportFile & " FROM IMAGES" & " WHERE ProjectName=" & projName
But I get the error:
No value given for one or more required parameters.
Mu SQL-fu is weak and not sure where I'm going wrong.
To conclude (and reduce slightly):
Dim projName
projName = "spoon"
cn.Execute "SELECT * INTO [text;HDR=Yes;Database=" & exportDir & _
";CharacterSet=65001]." & exportFile & " FROM IMAGES WHERE ProjectName='" & projName & "'"
As #allen-wang points out the reason for the error is lack of string value being identified as a string by encapsulating it in single quotes ('...').
However this and other issues such as SQL Injection weaknesses can be avoided by using the ADODB.Command to execute a Parameterised Query.
Dim cmd, sql, exportDir, exportFile
'Shouldn't be configurable outside this procedure.
exportDir = "..."
exportFile = "..."
Const adCmdText = 1
Const adParamInput = 1
Const adCmdVarChar = 200
Const adExecuteNoRecords = &H00000080
Set cmd = CreateObject("ADODB.Command")
sql = "SELECT * INTO [text;HDR=Yes;Database=" & exportDir & _
";CharacterSet=65001]." & exportFile & " FROM IMAGES WHERE ProjectName = ?"
With cmd
Set .ActiveConnection = cn
.CommandType = adCmdText
.CommandText = sql
Call .Parameters.Append(.CreateParameter("#ProjName", adVarChar, adParamInput, 255))
Call .Execute(, , adExecuteNoRecords)
End With
Just make sure that both exportDir and exportFile are not exposed or you leave the code open to SQL Injection.
Related
i have tried this code here to insert and show picture from database to picturebox : stackoverflow.com/questions/5624760/store-picture-to-database-retrieve-from-db-into-picturebox
and yeah, it is working , but when i tried to do update using the same syntax as insert it got this error :
this is the insert syntax i use :
Dim FileSize As UInt32
Dim mstream As New System.IO.MemoryStream()
gambar.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
mstream.Close()
call konek
strSQL = "insert into tbmahasiswa VALUES ('" & _
txtNIM.Text & "','" & _
txtNama.Text & "','" & _
Format(dtpTanggal.Value, "yyyy-MM-dd") & "','" & _
txtAlamat.Text & "','" & _
cboJurusan.Text & "',#gambar)"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
.Parameters.AddWithValue("#gambar", arrImage)
.ExecuteNonQuery()
End With
and this the code i use to show picture from database to picture box :
Dim imgData As Byte()
call konek
strSQL = "select * from tbMahasiswa where NIM ='" & txtNIM.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
Using rd = com.ExecuteReader
rd.Read()
If rd.HasRows Then
txtNama.Text = rd.Item(1)
dtpTanggal.Value = rd.Item(2)
txtAlamat.Text = rd.Item(3)
imgData = TryCast(rd.Item(5), Byte())
If imgData IsNot Nothing Then
Using ms As New MemoryStream(imgData)
gambar.Image = CType(Image.FromStream(ms), Image)
End Using
End If
End If
End Using
Both Insert and Retrieving Picture Code above is Working ! , and then i use this code for update :
Dim FileSize As UInt32
Dim mstream As New System.IO.MemoryStream()
gambar.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
mstream.Close()
call konek
strSQL = "update tbmahasiswa set Nama ='" & txtNama.Text & _
"', TglLahir ='" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"', Alamat ='" & txtAlamat.Text & _
"', Jurusan ='" & cboJurusan.Text & _
"', gambar =' #gambar" & _
"' where NIM ='" & txtNIM.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
.Parameters.AddWithValue("#gambar", arrImage)
.ExecuteNonQuery()
End With
and then i got the error like in the picture above, all other data is correctly saved except the picture, it become some unknown file blob 8 KB size.
i'm still newbie at insert , update, delete picture in VB, please can you tell me what is wrong with the Update syntax code , is it already true but i'm missing something ? or is it totally wrong with the syntax ? please i need your guide here...
UPDATE :
actually there is "call konek" above "STRSQL" in the code, "konek" have the code for open the mysql connection,i put it in the separate module, here the full code in my module :
Module modKoneksi
Public conn As New MySql.Data.MySqlClient.MySqlConnection
Public rd As MySql.Data.MySqlClient.MySqlDataReader
Public com As MySql.Data.MySqlClient.MySqlCommand
Public strSQL As String
Public Sub konek()
conn.Close()
strSQL = "server='localhost';user='root';pwd='';database='dbsekolah';"
Try
conn.ConnectionString = strSQL
conn.Open()
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End
End Try
End Sub
End Module
hope this makes you easier to solve my problem
I know its late but this is the working code for me :
For retrieving the record from database with pictures :
Call konek() 'Call the connection module'
strSQL = "select * from tbMahasiswa where ID ='" & txtID.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
Using rd = com.ExecuteReader
rd.Read()
If rd.HasRows Then
txtNIM.Text = rd.Item(1)
txtNama.Text = rd.Item(2)
dtpTanggal.Value = rd.Item(3)
txtAlamat.Text = rd.Item(4)
imgData = TryCast(rd.Item(6), Byte())
If imgData IsNot Nothing Then
Using ms As New MemoryStream(imgData)
gambar.Image = CType(Image.FromStream(ms), Image)
End Using
End If
cboJurusan.SelectedIndex = cboJurusan.FindStringExact(rd.Item(5))
End If
End Using
For inserting record to database with pictures :
Call konek()
strSQL = "Insert Into tbmahasiswa Values ('" & txtID.Text & _
"','" & txtNIM.Text & _
"','" & txtNama.Text & _
"','" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"','" & txtAlamat.Text & _
"','" & cboJurusan.Text & _
"',#gambar)"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
If opdGambar.FileName = Nothing Then 'opdGambar is a PictureBox name'
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes("man-icon.png") 'Insert field gambar using an existing file in debug folder if file does not exist in PictureBox'
Else
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes(opdGambar.FileName) 'Insert field gambar using an existing file in PictureBox'
End If
com.ExecuteNonQuery()
End With
For updating record to database with pictures :
Call konek()
Dim adapter As New MySql.Data.MySqlClient.MySqlDataAdapter("select gambar from tbmahasiswa where ID='" & txtID.Text & "'", conn)
Dim dt As New DataTable("gambar")
adapter.Fill(dt)
strSQL = "update tbmahasiswa set NIM='" & txtNIM.Text & _
"',Nama='" & txtNama.Text & _
"',TglLahir='" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"',Alamat='" & txtAlamat.Text & _
"',Jurusan='" & cboJurusan.Text & _
"' ,Gambar=#gambar where id='" & txtID.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
If opdGambar.FileName = Nothing Then
Dim row As DataRow = dt.Rows(0)
Using ms As New IO.MemoryStream(CType(row(0), Byte()))
Dim img As Image = Image.FromStream(ms)
gambar.Image = img
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = (CType(row(0), Byte())) 'field gambar will use the current existing file in database if PictureBox does not have a file'
End Using
Else
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes(opdGambar.FileName)
End If
com.ExecuteNonQuery()
End With
i hope for those who find the other answer a little confusing (like me), will find this answer helpful.
I have an Access database with a ton of tables, forms, and queries in it. With one of my forms I have an upload button that I would like to use for appending csv files to a specific table in the database.
I have an OnClick function for the button that I am getting hung up on..
Every time it get to the line
adoCSVConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strPathToTextfile & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited"""
It says that: the provider cannot be found or it is not installed properly..
Does this have anything to do with the settings in the Data Source Admin settings? Am I missing a reference?
Here is all of the code if you are interested in seeing what all I have
Private Sub uploadBTN_Click()
'Dim adoCSVConnection, adoCSVRecordset, strPathToTextfile
'Dim strCSVFile, adoJetConnection, adoJetCommand, strDBPath
Dim adoCSVConnection As ADODB.Connection
Dim adoCSVRecordset As ADODB.Recordset
Dim adoJetConnection As ADODB.Connection
Dim adoJetCommand As ADODB.Command
Set adoCSVConnection = New ADODB.Connection
Const adCmdText = &H1
' Specify path to CSV file. ex: c:\Scripts\
strPathToTextfile = "C:\Desktop\"
' Specify CSV file name. ex: Users.csv
strCSVFile = "testfile2.csv"
' Specify Access database file. ex: c:\Scripts\MyData.mdb
strDBPath = "\\folder\NewMasterclient.mdb"
' Open connection to the CSV file.
Set adoCSVConnection = CreateObject("ADODB.Connection")
Set adoCSVRecordset = CreateObject("ADODB.Recordset")
' Open CSV file with header line.
adoCSVConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strPathToTextfile & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited"""
adoCSVRecordset.Open "SELECT * FROM " & strCSVFile, adoCSVConnection
' Open connection to MS Access database.
Set adoJetConnection = CreateObject("ADODB.Connection")
adoJetConnection.ConnectionString = "DRIVER=Microsoft Access Driver (*.mdb);" _
& "FIL=MS Access;DriverId=25;DBQ=" & strDBPath & ";"
adoJetConnection.Open
' ADO command object to insert rows into Access database.
Set adoJetCommand = New ADODB.Command
Set adoJetCommand.ActiveConnection = adoJetConnection
adoJetCommand.CommandType = adCmdText
' Read the CSV file.
Do Until adoCSVRecordset.EOF
' Insert a row into the Access database.
adoJetCommand.CommandText = "INSERT INTO testfile2" & "(a, b, c, d, clientid, reg) " & "VALUES (" _
& "'" & adoCSVRecordset.Fields("a").Value & "', " _
& "'" & adoCSVRecordset.Fields("b").Value & "', " _
& "'" & adoCSVRecordset.Fields("c").Value & "', " _
& "'" & adoCSVRecordset.Fields("d").Value & "', " _
& "'" & adoCSVRecordset.Fields("clientid").Value & "')" _
& "'" & adoCSVRecordset.Fields("reg").Value & "')"
adoJetCommand.Execute
adoCSVRecordset.MoveNext
Loop
' Clean up.
adoCSVRecordset.Close
adoCSVConnection.Close
adoJetConnection.Close
End Sub
brdSrNo = txt_Board_SrNo.Text
usrname = txt_User_Name.Text
ndate = Format$(Now, "yyyy-mm-dd hh:mm:ss")
voltMeas1 = txt_VoltMes.Text
rs.Open "insert into duct_test values(" & brdSrNo & ",'" & ndate & "'," & usrname & ", " & voltMeas1 & ")", con, adOpenDynamic, adLockBatchOptimistic
'here I get the error'
I tried the above code but the error appears as:Incorrect syntax near','. Is there anyway to get the datetime like this:2015-10-30 17:09:22.000, as we get in sql
thanks #nabuchodonossor & #Fred, I got the Datetime pblm fixed. Now I got another error.. where, if voltMeas1=12.5 r something that takes an voltage measure... the error shows : "Arithmetic overflow error converting numeric to datatype numeric" ,In the sql table VoltageMeasure data type is Numeric(2,2).. can u suggest anthying?
you can also use the server time:
instead of:
rs.Open "insert into duct_test values(" & brdSrNo & ",'" & ndate & "'," & usrname & ",
you can write:
rs.Open "insert into duct_test values(" & brdSrNo & ", GETDATE(), " & usrname & ",
and implement the changes of mentioned by Fred
I can see a couple of things wrong here
You are inserting a record so you do not need a recordset as you are not returning anything. Use cmd .Execute instead of rs.Open.
usrname is a string so needs to be wrapped in single quotes '
Your final code should like more like:
Private Sub cmd_update_Click()
Dim strSQL As String
Dim con As ADODB.Connection
Set con = New ADODB.Connection
con.ConnectionString = "Provider=SQLOLEDB;Data Source=SUVI.suvi.local;InitialCatalog=SUVI;Database=BLS;uid=sa;pwd=123458;"
con.Open
strSQL = "insert into duct_test values(" & brdSrNo & ", GetDate(),'" & usrname & "', " & voltMeas1 & ")"
con.Execute strSQL, , adCmdText
con.Close
Set con = Nothing
End Sub
As a side note it is advisable to replace single quotes in any data input by a user with double single quotes. For example:
usrname = Replace$(usrname, "'", "''")
This will help against SQL injection attacks. Im not saying it will total prevent this but it will help.
If the date you are inserting is always the current date and time you can, as
nabuchodonossor point out, use GetDate().
I have created the code below to test whether I can run a query and retrieve a data from an SQL server table. And so far I can return the result using a MessageBox, but somehow I just don't know how to use this connection to update the table inside this Access file. Basically I want to use this as a front end file. Then, when the form is open it will automatically update the table inside this access file and load the data to the combo box as a list. I tried searching it here and read many discussions here and in Google but currently I can't find the right solution.
Option Compare Database
Sub LocalServerConn_Test()
Set conn = New adodb.Connection
Set rst = New adodb.Recordset
strDBName = "DataSet"
strConnectString = "Provider = SQLOLEDB.1; Integrated Security = SSPI; " & _
"Initial Catalog = " & strDBName & "; Persist Security Info = True; " & _
"Worksation ID = abc123;"
conn.ConnectionString = strConnectString
conn.Open
strSQL = "SELECT DISTINCT dbo.abc.abc123 FROM dbo.abc"
rst.Open Source:=strSQL, ActiveConnection:=strConnectString, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic
If rst.RecordCount = 0 Then
MsgBox "No records returned"
Else
rst.MoveFirst
Do While Not rst.EOF
MsgBox rst.Fields("abc123").Value
rst.MoveNext
Loop
End If
conn.Close
rst.Close
End Sub
You should be able to use code very similar to this:
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute _
"DELETE FROM LocalTable", _
dbFailOnError
cdb.Execute _
"INSERT INTO LocalTable (abc123) " & _
"SELECT DISTINCT abc123 " & _
"FROM " & _
"[" & _
"ODBC;" & _
"Driver={SQL Server};" & _
"Server=.\SQLEXPRESS;" & _
"Database=DataSet;" & _
"Trusted_Connection=yes;" & _
"].[dbo.abc]", _
dbFailOnError
Set cdb = Nothing
You can just keep the combo box bound to [LocalTable] and the updated values from the SQL Server table should appear.
how to save data from ms acess front end to ms sql backend?
It is nearly always better to use linked tables. This makes life much easier because you can update the SQL Server tables and views in more or less the same way that you would update an Access table. Another good way is to use pass-through queries : http://support.microsoft.com/kb/303968
That being said, here are a few rough notes.
The easiest way to get a useful ODBC string is to link a table using the wizard, you can then look it up using CurrentDB.TableDefs("NameOfLinkedTable").Connect
You can use the string like so:
Dim db As Database
Set db = CurrentDb
strConnect = "ODBC;Description=Test;DRIVER=SQL Server;" _
& "SERVER=ServerAddress;Trusted_Connection=Yes;DATABASE=DBName"
strSQL = "INSERT INTO [" & strConnect & "].[SomeSQLServerTable] (ID, AText) " _
& "SELECT a.ID, a.Descr FROM SomeAccessTable As a " _
& "LEFT JOIN [" & strConnect & "].[SomeSQLServerTable] s " _
& "ON s.ID=a.ID " _
& "WHERE s.ID Is Null"
db.Execute strSQL, dbFailOnError
Debug.Print db.RecordsAffected
You can also update with ADO. There is a great deal of information to be found here: http://msdn.microsoft.com/en-us/library/ms130978.aspx
You can get connection strings here: http://www.connectionstrings.com/
And some of the odder things you can do:
Dim cn As New ADODB.Connection
Dim RecsAffected As Long
Dim scn As String, sSQL As String
''Using SQL Server connection native client
scn = "Provider=SQLNCLI10;Server=ServerAddress;" _
& "Database=DBName; Trusted_Connection=yes;"
cn.Open scn
sSQL = "INSERT INTO NewSQLServerTable " _
& "SELECT * FROM OPENROWSET " _
& "('Microsoft.ACE.OLEDB.12.0','C:\docs\ltd.mdb';'Admin';, " _
& "'SELECT * FROM OldAccessTable')"
cn.Execute sSQL, RecsAffected
Debug.Print RecsAffected
Or
Dim cn As New ADODB.Connection
Dim RecsAffected As Long
Dim scn As String, sSQL As String
''Using Jet connection
Set cn = CurrentProject.Connection
strConnect = "ODBC;Description=Test;DRIVER=SQL Server;" _
& "SERVER=ServerAddress;Trusted_Connection=Yes;DATABASE=DBName"
sSQL = "INSERT INTO [" & strConnect & "].NewSQLServerTable " _
& "SELECT * FROM OldAccessTable"
cn.Execute sSQL, RecsAffected
''Using Jet & an external mdb
sSQL = "INSERT INTO [" & strConnect & "].NewSQLServerTable " _
& "SELECT * FROM OldAccessTable IN " _
& "'C:\docs\ltd.mdb'"
cn.Execute sSQL, RecsAffected
Debug.Print RecsAffected