Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOk.Click
Dim scan As String = "select ProductCode from products where ProductCode = '" & TextBox1.Text & "';"
connection.Open()
Dim cmd = New MySqlCommand(scan, connection)
Dim dr As MySqlDataReader = cmd.ExecuteReader
If dr.Read = True Then
MsgBox("Match found")
connection.Close()
Dim insert As String = "insert into salesreport (ProductName,ProductPrice) select products.ProductName,products.ProductPrice from products where products.ProductCode = '" & TextBox1.Text & "';"
connection.Open()
da = New MySqlDataAdapter(insert, connection)
da.Fill(ds, "salesreport")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "salesreport"
connection.Close()
Else
connection.Close()
MsgBox("No match found")
TextBox1.Text = ""
TextBox1.Select()
End If
End Sub
INSERT statements doesn't return records.
There is no sense in this situation to use a DataAdapter to INSERT a record.
Use the MySqlCommand.ExecuteNonQuery method to insert your record, then read the added row with a MySqlDataAdapter
Also, do not concatenate text, typed by your user, to build and use an sql text for the database engine. Your code could be easily used to create Sql Injection Attacks.
Dim scan As String = "select ProductCode from products " +
"where ProductCode = ?prodCode"
connection.Open()
Dim cmd = New MySqlCommand(scan, connection)
cmd.Parameters.AddWithValue("?prodCode", TextBox1.Text)
..........
Dim insert As String = "insert into salesreport (ProductName,ProductPrice) " +
"select products.ProductName,products.ProductPrice from products " +
"where products.ProductCode = ?prodCode"
cmd = new MySqlCommand(insert, connection)
cmd.Parameters.AddWithValue("?prodCode", TextBox1.Text)
cmd.ExecuteNonQuery()
da = New MySqlDataAdapter(scan, connection)
da.SelectCommand.Parameters.AddWithValue("?prodCode", TextBox1.Text)
da.Fill(ds, "salesreport")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "salesreport"
Related
Here is the code:
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
con = New SqlConnection("Data Source=LAPTOP-16IIQENS\SQLEXPRESS;Initial Catalog=students;Integrated Security=True")
con.Open()
cmd = New SqlCommand("select * from data where [Roll No.]=#[Roll No.]", con)
cmd.Parameters.Add("#Roll No.", SqlDbType.Int).Value = TextBox5.Text
Dim adp As New SqlDataAdapter(cmd)
Dim table As New DataTable()
adp.Fill(table)
If (table.Rows.Count() > 0) Then
DataGridView1.DataSource = table
TextBox2.Text = table.Rows(0)(0).ToString
TextBox1.Text = table.Rows(0)(1).ToString
TextBox3.Text = table.Rows(0)(2).ToString
TextBox4.Text = table.Rows(0)(3).ToString
Else
MessageBox.Show("No Data Found")
End If
End Sub
enter image description here
You can freely choose the name of your SQL parameter, it does not need to match the name of the field.
Thus, if you call your parameter #RollNo instead of #Roll No. (no space, no dot), you no longer need to escape the name in your SQL, which should fix your current issue.
Change:
cmd = New SqlCommand("select * from data where [Roll No.]=#[Roll No.]", con)
cmd.Parameters.Add("#Roll No.", SqlDbType.Int).Value = TextBox5.Text
to:
cmd = New SqlCommand("select * from data where [Roll No.]=#RollNo", con)
cmd.Parameters.Add("#RollNo", SqlDbType.Int).Value = TextBox5.Text
Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
I have this error in this code how can I solve it?
Imports System.Data.OleDb
Public Class yenikayit
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim isimT As String = ""
Dim soyisimT As String = ""
Dim tcNoT As String = ""
Dim yasT As String = ""
Dim cinsiyetT As String = ""
Dim perNoT As String = ""
Dim egDurT As String = ""
Dim meslekT As String = ""
Dim telNoT As String = ""
Dim emailT As String = ""
isimT = TextBox1.Text
soyisimT = TextBox2.Text
tcNoT = TextBox3.Text
yasT = TextBox6.Text
cinsiyetT = ComboBox1.Text
perNoT = TextBox4.Text
egDurT = ComboBox2.Text
telNoT = TextBox5.Text
meslekT = TextBox10.Text
emailT = TextBox9.Text
Dim query As String = "INSERT INTO Personel (isim,soyisim,Yas,Cinsiyet,Alan,Egitim,TC,personel_id,tel_no,email) VALUES(isimT,soyisimT,yasT,cinsiyetT,meslekT,egDurT,tcNoT,perNoT,telNoT,emailT)"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\MONSTER\Desktop\AGKS\AGKS\Database5.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Dim sonuc As Boolean
sonuc = cmd.ExecuteNonQuery()
If (sonuc = 1) Then
MsgBox("Girdiğiniz veriler kayıt olmuştur")
conn.Close()
End If
End Sub
End Class
this is the part of the code that give us error
Currently, your code does not add any parameter values to the command, hence the "No Values Given" error. The command doesn't recognize those names and assign them values just because you have declared them as variables above. You should make it clear that those are parameters in your sql query, and then set each parameter's value before executing the query:
Note that all instances of OleDbType.VarChar need to be replaced with the correct datatypes of your columns. I obviously have no way of knowing what types those columns are so I have just made them all VarChar, but you should adjust those to match your table schema.
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\MONSTER\Desktop\AGKS\AGKS\Database5.accdb"
Dim query As String = "INSERT INTO Personel (isim,soyisim,Yas,Cinsiyet,Alan,Egitim,TC,personel_id,tel_no,email) " & _
"VALUES (#isimT,#soyisimT,#yasT,#cinsiyetT,#meslekT,#egDurT,#tcNoT,#perNoT,#telNoT,#emailT)"
Using conn As OleDbConnection = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
With cmd
.Parameters.Add("#isimT", OleDbType.VarChar).Value = TextBox1.Text
.Parameters.Add("#soyisimT", OleDbType.VarChar).Value = TextBox2.Text
.Parameters.Add("#yasT", OleDbType.VarChar).Value = TextBox6.Text
.Parameters.Add("#cinsiyetT", OleDbType.VarChar).Value = ComboBox1.Text
.Parameters.Add("#meslekT", OleDbType.VarChar).Value = TextBox10.Text
.Parameters.Add("#egDurT", OleDbType.VarChar).Value = ComboBox2.Text
.Parameters.Add("#tcNoT", OleDbType.VarChar).Value = TextBox3.Text
.Parameters.Add("#perNoT", OleDbType.VarChar).Value = TextBox4.Text
.Parameters.Add("#telNoT", OleDbType.VarChar).Value = TextBox5.Text
.Parameters.Add("#emailT", OleDbType.VarChar).Value = TextBox9.Text
End With
conn.Open()
Dim sonuc As Boolean
sonuc = cmd.ExecuteNonQuery()
If (sonuc = 1) Then
MsgBox("Girdiğiniz veriler kayıt olmuştur")
End If
conn.Close()
End Using
Ok, try something like this:
Dim query As String = "INSERT INTO Personel (isim,soyisim,Yas,Cinsiyet,Alan,Egitim,TC,personel_id,tel_no,email) "
query +="VALUES(#isimT,#soyisimT,#yasT,#cinsiyetT,#meslekT,#egDurT,#tcNoT,#perNoT,#telNoT,#emailT)"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\MONSTER\Desktop\AGKS\AGKS\Database5.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
query.Parameters.AddWithValue("#isimT", TextBox1.Text)
cmd.Parameters.AddWithValue("#soyisimT", TextBox2.Text)
cmd.Parameters.AddWithValue("#tcNoT", TextBox3.Text)
cmd.Parameters.AddWithValue("#yasT", TextBox6.Text)
cmd.Parameters.AddWithValue("#cinsiyetT", ComboBox1.Text)
cmd.Parameters.AddWithValue("#perNoT", TextBox4.Text)
cmd.Parameters.AddWithValue("#egDurT", ComboBox2.Text)
cmd.Parameters.AddWithValue("#telNoT", TextBox5.Text)
cmd.Parameters.AddWithValue("#meslekT", TextBox10.Text)
cmd.Parameters.AddWithValue("#emailT", TextBox9.Text)
conn.Open()
Dim sonuc As Boolean
sonuc = cmd.ExecuteNonQuery()
If (sonuc = 1) Then
MsgBox("Girdiğiniz veriler kayıt olmuştur")
conn.Close()
End If
This should do the job. This should fix your exception.
I have a table that has columns CustomerCell and ReceiptType. I need to create a SELECT statement that displays every record that matches CustomerCell or ReceiptType.
I tried this code:
If TextBox1.Text.Trim.Length <> 0 OrElse CheckBox4.Checked = True Then
Dim Conn As New SqlConnection(constr)
Dim ds As New DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt] where (RcptCustCell = '" & TextBox1.Text & "') or ([RcptType] = 'Cash') "
Dim da As New SqlDataAdapter(sqlstr, Conn)
ds.Reset()
da = New SqlDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Call griddraw()
Conn.Close()
End If
Where Textbox1 is for CustomerCell and CheckBox4 is for ReceiptType. When I enter customer cell and receipt type I should see 2 records however with the above code I can see only one record.
This is my form:
As stated, look into parameters to avoid SQL injection and it does clear up your query a little more. I've put this together which may help. Might need a few tweaks for your application:
If TextBox1.Text.Trim.Length <> 0 OrElse CheckBox4.Checked = True Then
Dim dt As DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt] where (RcptCustCell = #RcptCustCell) or ([RcptType] = 'Cash') "
Using con As New SqlConnection(constr),
com As New SqlCommand(sqlstr, con)
com.Parameters.Add("#RcptCustCell", SqlDbType.VarChar).Value = TextBox1.Text
con.Open()
dt = New DataTable
dt.Load(com.ExecuteReader)
dgv.DataSource = dt
Call griddraw()
End Using
End If
Dim Conn As New SqlConnection(constr)
Dim ds As New DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt]"
If TextBox1.Text.trim.length <> 0 then
sqlstr += "where (RcptCustCell = '" & TextBox1.Text & "')"
endif
If chkPaymentCheck.checked then
if sqlstr.contains("where") = false then
sqlstr += "where RcptType = 'Check'"
EndIf
sqlstr += "or RcptType = 'Check'"
endif
Dim da As New SqlDataAdapter(sqlstr, Conn)
ds.Reset()
da = New SqlDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Call griddraw()
Conn.Close()
Try this and you can continue with the if statements to add more checks.
I have a form with button which should find records from Oracle database. I have three Textboxes on same form, and If text matches with values in fields of DB, Datagrid should show me this records. Here is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'connect to oracle DB
Dim oradb As String = "Data Source=orcl;User Id=Lucky;Password=Example;"
Dim conn As New OracleConnection(oradb)
conn.Open()
Dim SQL As String
SQL = "SELECT * FROM MyTable WHERE 1=1"
'SQL statement for 1st textbox
If Not TxtName.Text = "" Then
SQL = SQL & " AND USER_NAME =" & TxtName.Text
End If
'SQL statement for 2nd textbox
If Not TxtSurname.Text = "" Then
SQL = SQL & " AND USER_SURNAME =" & TxtSurname.Text
End If
'SQL statement for 3rd textbox
If Not TxtAddress.Text = "" Then
SQL = SQL & " AND USER_ADDRESS=" & TxtAddress.Text
End If
'select SQL statements and retrieve data using ExecuteReader
Dim cmd As New OracleCommand(SQL, conn)
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Dim dt As New DataTable
dt.Load(dr)
DataGridView1.DataSource = dt
End Sub
What am I doing wrong, nothing happens when button clicked?
This is a non-tested sample of the direction you could try:
Private Sub populateDataGridView()
'connect to oracle DB
Const connectionString As String = "Data Source=orcl;User Id=Lucky;Password=Example;"
Using conn As New OracleConnection(connectionString)
conn.Open()
Using cmd As New OracleCommand()
Dim SQL As String = "SELECT * FROM testtable "
Dim conjunction As String = " Where "
'SQL statement for 1st textbox
If Not TxtName.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " USER_NAME like :username")
cmd.Parameters.Add(New OracleParameter("username", String.Concat("%", TxtName.Text, "%")))
conjunction = " and "
End If
'SQL statement for 2nd textbox
If Not TxtSurname.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " user_surname like :usersurname")
cmd.Parameters.Add(New OracleParameter("usersurname", String.Concat("%", TxtSurname2.Text, "%")))
conjunction = " and "
End If
'SQL statement for 3rd textbox
If Not TxtAddress.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " user_address like :useraddress")
cmd.Parameters.Add(New OracleParameter("useraddress", String.Concat("%", TxtAddress.Text, "%")))
End If
'select SQL statements and retrieve data using ExecuteReader
cmd.Connection = conn
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Dim dt As New DataTable
dt.Load(dr)
DataGridView1.DataSource = dt
End Using
End Using
End Sub