I'm doing a cascading combo box which is connected to mysql. Is it possible to concatenate the query to have a straight query. Please see code below. TIA
'connection
dbCon = New MySqlConnection("Server=localhost;Database=kdi_forms;Uid=root;Pwd=MyNewPass")
strQuery = "SELECT prodName, prodCon FROM po_products WHERE prodCon =" & supply & ""
SQLCmd = New MySqlCommand(strQuery, dbCon)
SQLCmd.CommandTimeout = 30
'open query
dbCon.Open()
DR = SQLCmd.ExecuteReader
While DR.Read
Me.ComboBox2.Items.Add(DR.Item("prodName"))
End While
'done
DR.Close()
dbCon.Close()`
Yes, strQuery is just a string value. And like all strings, it can be concatenated... But as commented on your post already, the assumption is supply is an integer being passed from your comboBox and is and being selected from an integer field in the database. If supply is not an integer field in the database, or more generally speaking, if the value of supply could be anything other than an integer then you need to add single quotes in your query like this:
prodCon ='" & supply & "'"
This might be the problem:
prodCon =" & supply & "
Try to replace it with this:
prodCon ='" & supply & "'
Related
I know, there are lots of answers out there for this problem which should be trivial, but I did not find the right one. Here is my problem:
I open a record set with the following select statement:
SELECT twinecellar.produktnavn, twinecellar.land,
twinecellar.produkttype, twinecellar.år,
twinecellar.antall, twinecellar.poeng,
twinecellar.Picture, twinecellar.KR,
twinecellar.Poengsum, twinecellar.Sum
FROM twinecellar
WHERE (((twinecellar.land)=forms!fmainview!list13)
And ((twinecellar.produkttype)=forms!fmainview!list15))
ORDER BY twinecellar.poeng;
In the immidiate window I see that list 13 contains "france" and list 15 contains "red"
When I create a new Query with this statement, it's working, however, on the rst.Open gsStrQuery I get this error. gsStrQuery contains the select string.
Here is the code:
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Set conn = CurrentProject.Connection
Set rst = New ADODB.Recordset
rst.CursorType = adOpenDynamic
rst.ActiveConnection = conn
rst.Open gsStrQuery
Anybody out there with a good idea about this issue?
When you build your SQL string, concatenate the "parameters" values into the string.
gsStrQuery = "SELECT twinecellar.produktnavn, twinecellar.land, " & _
"twinecellar.produkttype, twinecellar.år, " & _
"twinecellar.antall, twinecellar.poeng, " & _
"twinecellar.Picture, twinecellar.KR, " & _
"twinecellar.Poengsum, twinecellar.Sum " & _
"FROM twinecellar " & _
"WHERE (((twinecellar.land)= '" & forms!fmainview!list13 & "') " & _
"And ((twinecellar.produkttype)= '" & forms!fmainview!list15 & "')) " & _
"ORDER BY twinecellar.poeng;"
That way your parameter values are hard coded into the string before you try to open the query.
(Also note: I added single quotes around your parameters to indicate they are strings.)
(Also also note: & _ is a line continuation for VBA so your SQL string concatenates properly. This allows you have a readable SQL code that's nicely indented.)
________________________________
There is also a way to use your current gsStrQuery and assign parameters values to the ADO recordset. (But I find the above Replacement method much easier to read when going back to review the code. The only drawback is you have to rebuild your SQL string each time your parameters change. But that overhead is minimal for non complicated queries.)
However, if you really want to use ADO parameters, you can find a useful description here.
Hope that helps :)
i have vb such as like this :
Sub inputdata()
Try
koneksi.Open()
***sql2 = "SELECT code_cust from customer where ('nama_cust= " & Me.cbcust.Text & "')"
cmd = New MySqlCommand(sql2, koneksi)
sql3.text=cmd.ExecuteNonQuery()***
sql = "insert into hsmaster(nohs,detailhs,beamasuk,satuanhs,idcust,asal) values ('" & Me.txtnohs.Text & "',"
sql += "'" & Me.rtdetail.Text & " ',"
sql += "'" & Me.txtbm.Text & " ',"
sql += "'" & Me.txtsatuan.Text & " ',"
sql += "'" & sql3 & " ',"
sql += "'" & Me.Cbcountry.Text & " ')"
cmd = New MySqlCommand(sql, koneksi)
cmd.ExecuteNonQuery()
MessageBox.Show("Insert data berhasil dilakukan")
Catch ex As Exception
MessageBox.Show("Insert data Gagal dilakukan")
Finally
koneksi.Close()
End Try
So i want save result of quert sql3 to slq3 , but the result was -1
Please advace ...
sql2 was query to customer table with clause name of customer was loading from combo box customer.
cbcust.text was from combo box loading data from table customer.
thanks for any kind help and sugestion.
ExecuteNonQuery is only for inserts/updates/deletes, queries that you aren't expecting to retrieve data back from. The -1 you are seeing is what databases return when executing a non-query to indicate whether the command was successful. You are correct to use ExecuteNonQuery on your second insert, but for your first select query if you want a value returned, you have to use
sql3.text = cmd.ExecuteScalar
or use a datareader
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
'check to make sure dr isnot nothing and read it, then
Dim returnValue as string = dr(code_cust)
ExecuteScalar is used for returning a single value and would probably work best in your case, datareader is used when expecting multiple columns and/or rows
You should be using parameters in your query too, but if using quotes like you are then:
***sql2 = "SELECT code_cust from customer where ('nama_cust= " & Me.cbcust.Text & "')"
needs the single quote moved like this:
***sql2 = "SELECT code_cust from customer where (nama_cust= '" & Me.cbcust.Text & "')"
because right now, that's a syntax error
I want to dynamically change the name of the column in my sqlstatement every time I select an item name similar of the columns on the cmbcategory comboBox. Then use it to get its data to be transferred to the cmbparts comboBox. Is it possible?
This is my sample code:
Public Sub cmbpartfill()
sqlstatement = "select '" & cmbcategory.Text & "' from tblparts"
Connect()
command = New MySqlCommand(sqlstatement, connection)
reader = command.ExecuteReader
While reader.Read
cmbpart.Items.Clear()
cmbpart.Items.Add(reader.Item(0).ToString)
End While
Disconnect()
End Sub
I would appreciate any help. Thanks.
This will work I think...............
sqlstatement = "select " & cmbcategory.Text & " from tblparts"
Edited:
Just try i am not sure............
sqlstatement = "select [" & cmbcategory.Text & "] from tblparts"
Use a backticks "`" instead of Single Quotes "'".
sqlstatement = "select `" & cmbcategory.Text & "` from tblparts"
is there any possible way to execute this without getting this error "There is already an open DataReader associated with this Connection which must be closed first." i already tried using "dr.close()" and i get another error that says "Invalid attempt to Read when reader is closed." can you help me out?
Heres my code:
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Label2.Text = AllPicker1.Text
Label3.Text = AllPicker2.Text
If AllPicker1.Value >= AllPicker2.Value Then
MsgBox("End Date Must be Greater!")
Else
Dim SQLstatement As String = "SELECT * FROM tblStudInfo,tbl_studentLog WHERE tblStudInfo.StudID = tbl_studentLog.StudentNumber AND tbl_studentLog.LoginDate BETWEEN '" & AllPicker1.Text & "' AND '" & AllPicker2.Text & "'"
OpenData(SQLstatement)
End If
End Sub
Public Sub OpenData(ByRef SQLstatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLstatement
.CommandType = CommandType.Text
.Connection = SqlConnection
dr = .ExecuteReader()
End With
While dr.Read
Dim SQLstatementSave As String = "INSERT INTO tbl_report (RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate) VALUES ('" & dr("StudID") & "','" & dr("Name") & "','" & dr("Course") & "','" & dr("Dept") & "','" & dr("LoginTime") & "','" & dr("LoginDate") & "') "
dr.Close()
Save(SQLstatementSave)
End While
SqlConnection.Close()
SqlConnection.Dispose()
SqlConnection.Open()
End Sub
Public Sub Save(ByRef SQLstatementSave As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLstatementSave
.CommandType = CommandType.Text
.Connection = SqlConnection
.ExecuteNonQuery()
End With
SqlConnection.Close()
SqlConnection.Dispose()
SqlConnection.Open()
End Sub
End Class
It seems you are using only one SqlConnection. For most database systems you cannot reuse the connection while you are reading from it. You can either read all data into memory / DataTable and work on the rows after that or use a different SqlConnection for your Inserts.
When working with SqlConnections, Readers and Commands I find the Using Statement very helpful to visualize object usage and creation.
We can reduce this down to a single query:
INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
SELECT StudID, Name, Course, Dept, LoginTime, LoginDate
FROM tblStudInfo
INNER JOIN tbl_studentLog ON tblStudInfo.StudID = tbl_studentLog.StudentNumber
WHERE tbl_studentLog.LoginDate BETWEEN #StartDate AND #EndDate
Note the use of the full INNER JOIN syntax. The older TableA,TableB syntax for joins should be avoided. Also note the use of placeholders for your dates. This is important.
Now I need to draw attention to a couple functions I saw: OpenData(), and Save().
Those two functions are fundamentally broken, because they force you to build your queries in a way that leaves you vulnerable to sql injection hacking. Someday soon, someone will put a value like this into a textbox that is included with a query:
';DROP Table tbl_studentLog;--
Think carefully about what would happen now if someone entered that into your AllPicker1.Text. It would be hard to do that to a date picker, but I'll bet you have other plain text fields that would allow this. The first character (single quote) in my proposed input would close the string literal in the query. The second character (semi-colon) would end the individual statement, but sql server won't stop executing code. The next set of characters make up an additional statement that would drop your table. The final two characters comment out anything that follows, to avoid sql server rejecting or not committing the command because of syntax errors. Yes, Sql Server will run that additional statement, if that is what you put in a textbox.
So, your methods as written are broken, because the only accept completed sql strings as input. Any function that calls into the database MUST also include a mechanism for accepting query parameters. You ultimately want to be running code more like this:
Public Sub CreateReport(ByVal StartDate As DateTime, ByVal EndDate As DateTime)
Dim sql As String = _
"INSERT INTO tbl_report " & _
" (RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate) " & _
" SELECT StudID, Name, Course, Dept, LoginTime, LoginDate " & _
" FROM tblStudInfo " & _
" INNER JOIN tbl_studentLog ON tblStudInfo.StudID = tbl_studentLog.StudentNumber " & _
" WHERE tbl_studentLog.LoginDate BETWEEN #StartDate AND #EndDate"
'.Net is designed such in most cases that you really do want a new SqlConnection for each query
'I know it's counter-intuitive, but it is the right way to do this
Using cn As New SqlConnection("Connection string"), _
cmd As New SqlCommand(sql, cn)
'Putting your data into the query using parameters like this is safe from injection attacks
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = StartDate
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = EndDate
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
One thing to point out here is that at first glance I don't close the connection. However, the Using block will ensure that the connection is closed promptly... even if an exception is thrown. Your existing code will leave the connection hanging in the case of a exception.
Also note that this neatly side-steps the whole issue of needing to execute a separate query while your reader is opened... but if you ever do really need to do this (it's rare), the answer is simple: use a separate connection.
Instead of:
Dim SQLstatementSave As String = "INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
VALUES ('" & dr("StudID") & "','" & etc.
Try using .ToString on your DR() references.
Dim SQLstatementSave As String = "INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
VALUES ('" & dr("StudID").ToString & "','" & etc.
I have created a form in Access 2010 that is used to insert data into an existing table. The table contains a Keywords field, Source combo box, and a Code text box where i write the data to be inserted and there is a button for executing the query. The code for the form is:
Private Sub cmd_go_Click()
Dim insertstring As String
insertstring = "INSERT INTO KWTable (KW, Source, Code) VALUES('" & text_key.Value & "','" & combo_source.Value & "','" & txt_code.Value & "');"
DoCmd.RunSQL insertstring
End Sub
The code is simple, it inputs the data to the table so i can reference it for future use. Now the problem I am having is that when I try to add long bits of code that I use in SQL Server i get a syntax missing expression error which I am assuming is coming from the single quotes since the code is from SQL. I am getting the error because when i am trying to store a code i used in SQL Server it uses single quotes which access does not recognise. I think if I try to write in the code for the insert form something to help convert the single quotes into double quotes, then reconvert them back to single quoteswill help solve the problem. I just cant figure out how to do it and could really use some help.
Thank You
You can avoid trouble with included quotes in your inserted text by using a parameter query.
Consider an approach such as this for cmd_go_Click().
Dim strInsert As String
Dim db As DAO.database
Dim qdf As DAO.QueryDef
strInsert = "PARAMETERS pKW TEXT(255), pSource TEXT(255), pCode TEXT(255);" & vbCrLf & _
"INSERT INTO KWTable (KW, Source, Code) VALUES (pKW, pSource, pCode);"
'Debug.Print strInsert
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strInsert)
qdf.Parameters("pKW") = Me.text_key.value
qdf.Parameters("pSource") = Me.combo_source.value
qdf.Parameters("pCode") = Me.txt_code.value
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
However, I don't understand how JoinCells() fits in.
I use a function that handles Null Values, and escapes single quotes (by converting them to two single quotes) when creating SQL statements directly:
Function SafeSQL(ByVal pvarSQL As Variant) As String
SafeSQL2 = Replace(Nz(pvarSQL, ""), "'", "''")
End Function
Then in your routine you would have:
insertstring = "INSERT INTO KWTable (KW, Source, Code) VALUES('" & SafeSQL(text_key.Value) & "','" & SafeSQL(combo_source.Value) & "','" & SafeSQL(txt_code.Value) & "');"