I have this module call Procedure , and I want to parametrize it. I'm sending a string as the query to the procedure module . I look already in google but I could not find the answer to my problem.
Procedures.Insert("INSERT INTO Technician (tec_name, tec_email, rol_id) VALUES ('" & txt_tech.text & "', '" & txt_tech_email.text & "', " & cbo_tech_role.selectvalue.tostring & ")", "Technican Add Correct")
========================================
I will probably change it for .....
Procedures.Insert("INSERT INTO Technician (tec_name, tec_email, rol_id) VALUES ('#tech_name', '#tech_email', '#tech_role' ")", "Technican Add Correct")
================ But I dont know where I can Parametrized
Public Sub Insert(query As String, msg As String)
Dim cn As New SqlConnection(cs)
Dim cmd As New SqlCommand
Try
cn.Open()
With cmd
.CommandType = CommandType.Text
.CommandText = query
.Connection = cn
.Parameters.AddValueWith("#tech_name",txt_tech_name.text)
.Parameters.AddValueWith("#tech_email",txt_tech_email.text)
.Parameters.AddValueWith("#tech_rol",txt_tech_role.selectValue.tostring)
.ExecuteNonQuery()
End With
MessageBox.Show(msg, "INSERT", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, ". : : ERROR : : .", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then
cn.Close()
cn = Nothing
End If
End Try
End Sub
Because I have a module that is separate from the main code , I'm not able to call the textboxes because they are separate from the main module ... any idea on how to do this ?? ... Dont be hard .. This is my 14 week working with VB.. :/
Add to the Insert function parameter for SqlParameters
Public Sub Insert(query As String, msg As String, params As SqlParameter())
Dim cn As New SqlConnection(cs)
Dim cmd As New SqlCommand
Try
cn.Open()
With cmd
.CommandType = CommandType.Text
.CommandText = query
.Connection = cn
If params IsNot Nothing AndAlso params.Count > 0 Then
.Parameters.AddRange(params)
End If
.ExecuteNonQuery()
End With
MessageBox.Show(msg,
"INSERT",
MessageBoxButtons.OK,
MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, ". : : ERROR : : .",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
Finally
If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then
cn.Close()
cn = Nothing
End If
End Try
End Sub
Then use it like this:
Dim query As String = "INSERT INTO Technician (tec_name, tec_email, rol_id) VALUES (#tech_name, #tech_email, #tech_role)"
Dim msg As String = "Technican Add Correct"
Dim params As SqlParameter() = {New SqlParameter("#tech_name",txt_tech_name.text),
New SqlParameter("#tech_email",txt_tech_email.text),
New SqlParameter("#tech_rol",txt_tech_role.selectValue.tostring)}
Procedures.Insert(query, msg, params)
Using array of SqlParameter give you a possibility for using same function with parameter type other then string
You can have it this way... it works for me.
String query = "INSERT INTO Technician(tec_name, tec_email, rol_id) VALUES(#tech_name, #tech_email, #tech_rolr)"
params = {"tech_name", "tech_email", "tech_rolr"}
values = {"" & txt_tech_name.text, "" & txt_tech_email.text, "" & txt_tech_role.selectValue.tostring()}
SaveUpdateDelete(query, params, values)
under module, you can put this
Public params() As String
Public values() As String
Public Sub SaveUpdateDelete(ByVal sql As String, ByVal parameters() As String, ByVal Values() As String)
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
command = New MySqlCommand(sql, con)
For i = 0 To parameters.Count - 1
command.Parameters.AddWithValue("#" & parameters(i).ToString, Values(i))
Next
command.CommandText = sql
command.ExecuteNonQuery()
con.Close()
End Sub
the method SaveUpdateDelete is applicable for adding, updating and deleting data.. your code will only differ in query... "insert, update, delete"
Related
I having problems understanding why my one of my comboboxes displays a filtered search but the other one doesn't, I am using the same code for both comboboxes but modified some SQL queries linked to my database. I have also noticed that when I remove or comment out the code for any one of the comboboxes the the filtered search happens for the one hasn't been commented or removed. I also used an "If, Else" statement but still doesn't work. I would also want for both comboboxes to be used to filter a datagridview. Just to keep in mind once the item is selected from the combobox a search button is pressed to filer/display data into the datagridview.
Kind Regards
Here is my code and form:
[Redundant Data being displayed] https://i.stack.imgur.com/JEQI4.png
[ComboBox Brand works as intended] https://i.stack.imgur.com/6YyBf.png
[ComboBox Category displays everything rather than displaying the category chosen] https://i.stack.imgur.com/oEfII.png
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
If Not CmbBrand.SelectedIndex & CmbCategory.SelectedIndex = Nothing Then
BrandDisplay()
ElseIf CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
CategoryDisplay()
ElseIf Not CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
End If
cn.Close()
End Sub
Private Sub BrandDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STBrand Like #BrandSearch"
.Parameters.AddWithValue("#BrandSearch", "%" & CmbBrand.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Brand from the drop down list", "Brand", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
Private Sub CategoryDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
```
It is a good idea to separate your User Interface code from you database code. Your event procedure code should be rather brief.
Declare your Connections, Commands and DataReaders in the method where they are used so they can be disposed. Using...End Using blocks do this for us; they also close the connection. Pass your connection string directly to the constructor of the connection.
We have a different CommandText and ParametersCollection for each possibility. For Sql Server use the Add method rather than AddWithValue.
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim dt = GetSearchData(CmbBrand.Text, CmbCategory.Text)
DGVRecord.DataSource = dt
End Sub
Private Function GetSearchData(Brand As String, Category As String) As DataTable
Dim dt As New DataTable
Dim sqlString = "Select * From From TblStock "
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand()
cmd.Connection = cn
If Not String.IsNullOrEmpty(Brand) AndAlso Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch And STBrand = #BrandSearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Brand) Then
cmd.CommandText = sqlString & "Where STBrand = #BrandSearch;"
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
Else
cmd.CommandText = sqlString & ";"
End If
cn.Open()
Using reader = cmd.ExecuteReader()
dt.Load(reader)
End Using
End Using
Return dt
End Function
For better understanding you need to change those first "if... then... else...".
If the combobox is not selected it will have value -1 so you can do it like this:
Dim bBrandIsSelected as boolean = CmbBrand.SelectedIndex <> -1
Dim bCategoryIsSelected as boolean = CmbCategory.SelectedIndex <> -1
Now you can build the code more easily like:
If bBrandIsSelected AndAlso bCategoryIsSelected then
' do something
else
if bBrandIsSelected then
BrandDisplay()
else
if bCategoryIsSelected then
CategoryDisplay()
End if
End if
End if
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
I'm trying to create a Login Form using Visual Basic 2015 in Visual Studio. I've followed the instructions from a video that I've watched, however, an error occurred when I tried to run the code.
Here's the codes I've done so far:
Private Sub picgo1_Click(sender As Object, e As EventArgs) Handles picgo1.Click
openConn()
Dim dr As SqlDataReader
Dim cmd As SqlCommand
Dim sqlsyntax As String
cmd = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.Connection = conn
sqlsyntax = "select * from tblusers where user = '" & txtuser.Text & "' and pass = '" & txtpass.Text & "'"
cmd.CommandText = sqlsyntax
dr = cmd.ExecuteReader()
If dr.HasRows Then
MsgBox("Access Granted! Welcome '" & txtuser.Text & "'")
Else
MsgBox("Access Denied! Incorrect Username or Password!")
End If
conn.Close()
cmd.Dispose()
End Sub
Another for Module
Imports System.Data.SqlClient
Module ModuleConnections
Public conn As SqlConnection
Sub openConn()
Try
conn = New SqlConnection("Data Source=E:\HRIMS\HRIMS V1.0\WINDOWSAPPLICATION2\HRIMSDB.MDF;Integrated security=True")
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Catch ex As Exception
MsgBox("Connecting to Database Failed" & ex.ToString)
End Try
End Sub
End Module
When I tried to run the form, here is the error I'm getting. Then when I pressed ok, it points me to this line.
I'm still trying to learn, so please don't be too hard on me :D
Thank you in advance.
Try:
Public conn As SqlConnection
Public Sub openConn()
conn = New SqlConnection(CONNECTIONSTRING)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Return conn
End Function
Login code:
Using cmd As New SqlCommand("SELECT *
FROM tblusers
WHERE user = #userName
AND pass = #userPass", openConn)
'Parameterize your query to be safe from SQL Injection
cmd.Parameters.AddWithValue("#userName", txtuser.Text)
cmd.Parameters.AddWithValue("#userPass", txtpass.Text)
Using rdr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleResult)
Dim Login As Object = 0
If rdr.HasRows Then
rdr.Read
Login = rdr(Login)
End If
If Login = Nothing Then
MsgBox("Access Denied! Incorrect Username or Password!")
Else
'MsgBox("Access Granted! Welcome '" & txtuser.Text & "'")
MsgBox(String.Format("Access Granted! Welcome {0}!", txtuser.text)
End If
End Using
End Using
I have, for over a month, tried in vain to resolve this. I am using SQLite and trying to write a simple check to see if i can connect to the database. I found some code here that was supposed to do just that.
Public Function ConnExist(strDB) As Boolean
Dim SQLconnect As New SQLite.SQLiteConnection()
Try
Using Query As New SQLiteCommand()
SQLconnect.ConnectionString = "DataSource=" & strDB & ";Version=3;New=False;Compress=True;"
SQLconnect.Open()
With Query
.Connection = SQLconnect
.CommandText = "SELECT * FROM tbltest"
End With
Query.ExecuteNonQuery()
SQLconnect.Close()
End Using
'SQLconnect.ConnectionString = "Data Source=" & strDB & ";Version=3;New=False"
'SQLconnect.Open()
'SQLconnect.Close()
Catch ex As Exception
MsgBox(ex.Message)
'Return False
End Try
Return True
End Function
I know the database is at the location specified. On the SQLconnect.Open() part it errors out and tells me datasource cannot be empty. I opened the database using DB Browser and it is not corrupt. What am I doing wrong?
This is how I build my connection string for SQLite.
Dim constr As String = "Data Source=""" & FullFilePath & """;Pooling=true;FailIfMissing=false"
Think you are just missing the Double Quotes around the path.
Public Function ConnExist(strDB) As Boolean
Dim cs As String
Dim cnn As New SQLiteConnection
Dim cmd As New SQLiteCommand
cs = "Data Source=" & strDB & ";Version=3;New=False;"
If (IO.File.Exists(strDB)) Then
cnn = New SQLiteConnection(cs)
Try
cnn.Open()
cmd = cnn.CreateCommand()
cmd.CommandText = "SELECT * FROM tblSettings"
cmd.ExecuteNonQuery()
cnn.Close()
cmd.Dispose()
cnn.Dispose()
Catch ex As Exception
Return False
Exit Function
End Try
Else
Return False
Exit Function
End If
Return True
End Function
i have a problem with supply parameter to store procedure with odbc, this is my procedure in module form Public cmd As OdbcCommand
Private Sub cmdapprove_Click(sender As Object, e As EventArgs) Handles cmdapprove.Click
cmd = New OdbcCommand("select * from mk_cuti where mk_nik='" & txtnik.Text & "'", conn)
rd = cmd.ExecuteReader
rd.Read()
rd.Close()
Call opendb()
If txtstatus.Text = 1 Then
Using (conn)
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_update_data_trans_cuti_terbawa"
cmd.Parameters.AddWithValue("#mk_nik", Me.txtnik.Text)
cmd.ExecuteNonQuery()
End Using
Dim updatestatus_hrd As String = "Update input_cuti set status_hrd=1 " & _
"where no_input='" & txtnoinput.Text & "'"
cmd = New OdbcCommand(updatestatus_hrd, conn)
cmd.ExecuteNonQuery()
Call datacutikaryawan()
Else
Dim updatestatus_hrd As String = "Update input_cuti set status_hrd=1 " & _
"where no_input='" & txtnoinput.Text & "'"
cmd = New OdbcCommand(updatestatus_hrd, conn)
cmd.ExecuteNonQuery()
Call datacutikaryawan()
End If
End Sub
when i run this procedure, i got massage this
ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Procedure
or function 'sp_update_data_trans_cuti_terbawa' expects parameter
'#mk_nik', which was not supplied.
I think anyone can help me? please
Here's one with your class:
Dim conn As New OdbcConnection(sConnString)
conn.Open()
Dim sqlCommand As String = "sp_update_data_trans_cuti_terbawa #mk_nik='" & Me.txtnik.Text & "'"
Dim command As New OdbcCommand(sqlCommand)
command.CommandType = CommandType.StoredProcedure
command.Connection = conn
command.ExecuteNonQuery()
Aight, I'm off to the nearest pub.
conn.execute("sp_update_data_trans_cuti_terbawa #mk_nik='" & Me.txtnik.Text & "'")
I have module with this
Imports System.Data.Odbc
Imports System.Data
Module koneksi
Public conn As OdbcConnection
Public str As String
Public da As OdbcDataAdapter
Public ds As DataSet
Public cmd As OdbcCommand
Public rd As OdbcDataReader
Sub opendb()
str = "Dsn=pmscuti;database=att2000;server=pams-01;uid=sa;pwd=pams123"
conn = New OdbcConnection(str)
If conn.State = ConnectionState.Closed Then
Try
conn.Open()
'MsgBox("Connection Successfully")
Catch ex As Exception
MsgBox(ex.Message)
Application.Exit()
End Try
End If
End Sub
End Module
can i know where the problem?