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
Related
I'm trying to insert data in MYSQL and get the latest ID but the problem is I'm Inserting Duplicate data
Is my syntax is wrong or something?
connection.Open()
insertString = "INSERT INTO `daily_report`(`saan_nalaman`,`purpose`, `usual_time`, `apps`,`feedback`,`userid`, `survey_at_what_blh`) VALUES ('" & txtq1.Text & "', '" & txtq2.Text & "', '" & txtq3.Text & "', '" & txtq4.Text & "', '" & txtq5.Text & "', '" & Utilities.UserID & "', '" & Login.RichTextBox1.Text & "');SELECT last_insert_id();"
command = New MySqlCommand(insertString, connection)
reader = command.ExecuteReader
connection.Close()
connection.Open()
TextBox1.Text = command.ExecuteScalar
connection.Close()
Declare and dispose your database objects in the method where they are used. Using blocks handle this for us even if there is an error. Always use parameters to avoid sql injection. Also, it makes the sql command easier to read and write without all the concatenation and single quotes. A single ExecuteScalar will accomplish both the insert and the select.
Private ConStr As String = "Your connection string"
Private Sub GetID()
Dim insertString = "INSERT INTO `daily_report`(`saan_nalaman`,`purpose`, `usual_time`, `apps`,`feedback`,`userid`, `survey_at_what_blh`) VALUES (#saan, #purpose, #time, #apps, #feedback, #userid, #survey) SELECT last_insert_id();"
Dim id As Integer
Using Command As New MySqlCommand(insertString, New MySqlConnection(ConStr))
With Command.Parameters
.AddWithValue("#saan", txtq1.Text)
.AddWithValue("#purpose", txtq2.Text)
.AddWithValue("#time", txtq3.Text)
.AddWithValue("#apps", txtq4.Text)
.AddWithValue("#feedback", txtq5.Text)
.AddWithValue("#userid", Utilities.UserID)
.AddWithValue("#survey", Login.RichTextBox1.Text)
End With
Command.Connection.Open()
id = CInt(Command.ExecuteScalar)
End Using
TextBox1.Text = id.ToString
End Sub
information error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')-Tanggalpjm)+1 As Lmpinjam, IFF (LMPINJAM>5,(LMPINJAM-5)*500,0) AS DENDA From t' at line 1
this my databse:
how this syntax work:
1. Select the member number in the combobox or type the member number in the Combobox (Book will appear that has been borrowed on the second grid
2. type the code of the Book (eg B001, B002, B003 etc.) on the first grid in the first column, if the file has never been borrowed, a message will appear that the Book has never been borrowed.
3. cancellation of returns on certain Book codes can be done by pressing ESC in the relevant Book row "
4. before being saved, fill in the "payment amount first"
denda = payment
its error on DataGridView1 coz this script use SQL access and my vb use phpmyadmin as database
so how to change this syntax to phpmyadmin SQL?
("Select distinct tbBuku.NomorBK,tbdetailpjm.Nomorpjm,Judul,JumlahBK,tanggalpjm, (Date()-Tanggalpjm)+1 As Lmpinjam, IFF (LMPINJAM>5,(LMPINJAM-5)*500,0) AS DENDA From tbAnggota,tbPinjam,tbBuku,tbDetailpjm Where tbBuku.NomorBK=tbDetailpjm.NomorBK And tbPinjam.Nomorpjm=tbDetailpjm.Nomorpjm And tbAnggota.Nomoragt=Pinjam.Nomoragt And tbAnggota.Nomoragt='" & CmbNomoragt.Text & "' AND tbDETAILPJM.NomorBK='" & DgLaporan.Rows(e.RowIndex).Cells(0).Value & "' AND DETAILPJM.JUMLAHBK>0", conn)
full script:
Imports MySql.Data.MySqlClient
Imports System.Math
Private Sub DgLaporan_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DgLaporan.CellEndEdit
If e.ColumnIndex = 0 Then
CMD = New MySqlCommand("select NomorBK from tbanggota,tbpinjam,tbdetailpjm where NomorBK ='" & DgLaporan.Rows(e.RowIndex).Cells(0).Value & "' and tbpinjam.nomorpjm=tbdetailpjm.nomorpjm and tbanggota.nomoragt=tbpinjam.nomoragt and tbanggota.nomoragt='" & CmbNomoragt.Text & "' AND tbdetailpjm.JUMLAHBK>0", conn)
RD = CMD.ExecuteReader
RD.Read()
If Not RD.HasRows Then
MsgBox(" " & LblNamaAgt.Text & " tidak meminjam kode Buku " & DgLaporan.Rows(e.RowIndex).Cells(0).Value & "")
Call HapusBaris()
Exit Sub
RD.Close()
End If
RD.Close()
CMD = New MySqlCommand("Select distinct tbBuku.NomorBK,tbdetailpjm.Nomorpjm,Judul,JumlahBK,tanggalpjm, (Date()-Tanggalpjm)+1 As Lmpinjam, IFF (LMPINJAM>5,(LMPINJAM-5)*500,0) AS DENDA From tbAnggota,tbPinjam,tbBuku,tbDetailpjm Where tbBuku.NomorBK=tbDetailpjm.NomorBK And tbPinjam.Nomorpjm=tbDetailpjm.Nomorpjm And tbAnggota.Nomoragt=Pinjam.Nomoragt And tbAnggota.Nomoragt='" & CmbNomoragt.Text & "' AND tbDETAILPJM.NomorBK='" & DgLaporan.Rows(e.RowIndex).Cells(0).Value & "' AND DETAILPJM.JUMLAHBK>0", conn)
RD = CMD.ExecuteReader
RD.Read()
If RD.HasRows Then
DgLaporan.Rows(e.RowIndex).Cells(1).Value = RD.Item(1)
DgLaporan.Rows(e.RowIndex).Cells(2).Value = RD.Item(2)
DgLaporan.Rows(e.RowIndex).Cells(3).Value = RD.Item(3)
DgLaporan.Rows(e.RowIndex).Cells(4).Value = RD.Item(4)
DgLaporan.Rows(e.RowIndex).Cells(5).Value = RD.Item(5)
DgLaporan.Rows(e.RowIndex).Cells(6).Value = RD.Item(6)
DgLaporan.CurrentCell = DgLaporan.Rows(e.RowIndex).Cells(0)
Call TotalKEMBALI()
Call TotalDENDA()
Call pembayaran()
Else
MsgBox(" " & LblNamaAgt.Text & " tidak meminjam kode Buku " & DgLaporan.Rows(e.RowIndex).Cells(0).Value & "")
End If
End If
RD.Close()
End Sub
The DATE function is used to extract a date from a string, thus it expects you to pass a parameter to it.
If you want to get today's date use the CURRENT_DATE function instead:
(CURRENT_DATE()-Tanggalpjm)+1
Also, your code is vulnerable to SQL Injection. Using regular string concatenation to build queries has been discouraged for many years. Look into how to use SQL Parameters.
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 this simple code of vba access to update product in the database. But when I debug, it stops at the DoCmd statement and got run-time error. I've made research about this kind of error and code, and had changed the code but still caused an error. Below is my simple code to update the product value.
Sub UpdateProduct()
Dim mySql As String
mySql = "UPDATE " & Forms!UPDATE_PRODUCT!cbxLensType _
& " SET LOT_NO = " & Forms!UPDATE_PRODUCT!txtLotNo _
& " WHERE EAN_CODE = " & Forms!UPDATE_PRODUCT!txtEan & ";"
DoCmd.RunSQL mySql
End Sub
Could you help me to explain what is the problem to my code? Is it because of the update syntax?
Thanks in advance.
**New to access vba
Since EAN_CODE is Text type you need to enclose it inside single quotes.
Sub UpdateProduct()
Dim mySql As String
mySql = "UPDATE [" & Forms!UPDATE_PRODUCT!cbxLensType _
& "] SET LOT_NO = " & Forms!UPDATE_PRODUCT!txtLotNo _
& " WHERE EAN_CODE = '" & Forms!UPDATE_PRODUCT!txtEan & "';"
DoCmd.RunSQL mySql
End Sub
If LOT_NO is also a Text type, make sure that it is also enclosed in Single quotes.
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 & "'