VB Return a single value from SQL - sql

I am trying to retrieve a single integer value. There will always be one and only one record in the DB for this select. I want to connect, retrieve store and display this value. is this executescalar the way to go?
Dim sqlquery As String
Dim ConnectionString As String
ConnectionString = "Server=" + ServerName + "\" + InstanceName + "; Database=" + DatabaseName + "; User Id=" + UserId + ";Password=" + Password + ";"
sqlquery = "SELECT severity FROM from dbo.SettingsSub where SEB_SettingsID = 'Severity"
'Connect
Using conn As SqlConnection = New SqlConnection(ConnectionString)
conn.Open()
Using comm As SqlCommand = New SqlCommand(sqlquery, conn)
CurrentSeverity = Convert.ToInt32(comm.ExecuteScalar())
txtCurrentSeverity.Text = CurrentSeverity
conn.Close()
End Using 'comm

"There will always be one and only one record in the DB for this select."
Even though you know that this is the case you should always use a "Select top 1" statement in this scenario as you never know what will happen in the future.

Related

Log-In module with SQL Server not working

I have created two form for Login module. One for the admins and one for the customers.
Admin:
Dim con As SqlConnection = New SqlConnection("Data Source=LEGIONPC;Initial Catalog=master;Integrated Security=True")
Dim cmd As SqlCommand = New SqlCommand("select * from tbAdmin where admin_id=' " + txtUsername.Text + " ' and admin_password='" + txtPassword.Text + "'", con)
Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
If (dt.Rows.Count > 0) Then
MessageBox.Show("Correct.", "Log-In")
Else
MessageBox.Show("Invalid.", "Log-In")
End If
Customer:
Dim con As SqlConnection = New SqlConnection("Data Source=LEGIONPC;Initial Catalog=master;Integrated Security=True")
Dim cmd As SqlCommand = New SqlCommand("select * from tbLogin where username=' " + txtUsername.Text + " ' and pass='" + txtPassword.Text + "'", con)
Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
If (dt.Rows.Count > 0) Then
MessageBox.Show("Correct.", "Log-In")
Else
MessageBox.Show("Invalid.", "Log-In")
End If
They are basically just the same, except that both of them are in different form and are based on different tables. But for some reason, the Customer log in is not working, even though the inputs are correct and matches the records in database, it always shows it's invalid.
In database, tbAdmin's primary key is admin_id and tbCustomer's primary key is username.
Is it possible that it's kind of interrupting the connection because they basically all have the same variable name? But they're in different form and admin log in is perfectly fine.
I would like to apologize, I am new to connecting vb.net to sql.
one thing I notice is you leave a space between the colon
Try this
"select * from tbLogin where username='" & txtUsername.Text & "' and pass='" & txtPassword.Text & "'"
Also if you do not want it to be case sensitive you always use 'like'
"select * from tbLogin where username like '" & txtUsername.Text & "' and pass like '" & txtPassword.Text & "'"

How can I realize a refresh button of DataGrid WPF

How can I make a refresh button for mine DB which withdraws to DataGrid? I have this:
Dim con As New MySqlConnection()
con.ConnectionString = "server =" + server + ";" + "user id=" + username + ";" + "password= " + password + ";" + "database =" + database
con.Open()
'Dim query As String
'query = "select * from suspects_arrests"
Dim cmd As New MySqlCommand()
cmd.CommandText = "select * from suspects_arrests"
cmd.Connection = con
Dim sqlAdap As New MySqlDataAdapter(cmd)
Dim dt As New DataTable("suspects_arrests")
sqlAdap.Fill(sqlData)
DataSuspects.ItemsSource = sqlData.DefaultView
con.Close()
But this is duplicating records. DataSuspects.Items.Refresh/Clear not working. On Items.Clear() goes this error:
The operation is invalid when the ItemsSource is in use. Instead, access and modify items using ItemsControl.ItemsSource
Not pressed (screenshot)
When pressed

How to quick update MySQL table through a loop using VB.net

My code for updating mysql table having more than 2000 rows through a loop using VB.net is working fine but too slow. Is there any way to update it faster ? Anybody please help. Thanks. My code is given below.
Dim mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "server=localhost;user id=root;password=1234;database=Share"
mysqlconn.Open()
Dim adapter As New MySqlDataAdapter("SELECT * FROM name_list;", mysqlconn)
Dim datatable As New DataTable()
adapter.Fill(datatable)
Dim cmd As New MySqlCommand
cmd.Connection = mysqlconn
Dim sql As String
Dim i as integer = 0
While i <= datatable.Rows.Count - 1
Dim sy As String = datatable.Rows(i).Item(3).ToString.Trim
sql = "UPDATE Name_list Set Numerology = '" & "N-" & variable1 & " S- " & variable2 & "',FSTLetter = '" & variable3 & "',Timing = '" & vriable4 & "',P_Numerology = '" & variable5 & "' WHERE Symbol = '" & sy & "'"
sy = ""
cmd.CommandText = sql
cmd.ExecuteNonQuery()
i = i + 1
End While
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
DataGridView1.Refresh()
Don't name variables the same as class names (DataTable, datatable) vb.net is case insensitive so it confuses intellisense.
Database connections and commands need to closed and disposed.
Using blocks do this for you even if there is an error.
You can set the connection string by passing it directly to the constructor of the connection. Likewise, you can set the command text and the connection by passing to the constructor of the command.
Don't open the connection until right before it is used. In this case we don't need a DataAdapter but if you are using one it is not necessary to open the connection at all. The .Fill method of the DataAdapter will open and close the connection. However if the DataAdapter finds an open connection it will leave it open.
To avoid confusion, I created 2 data tables. I used a single connection but I opened and closed it each time it is used. It is not disposed until the last End Using.
The first command retrieves only the sy column. Replace Column4_Name with the actual column name. We don't want to pull down data we don't need so no Select *.
Always use parameters to avoid sql injection which can damage your database. You need to check your database for the types of the fields. I had to guess. Each parameters value is set except sy which changes on each iteration.
No need to close the connection after the last Select command since the final End Using will close and dispose.
After the connection is closed we update the user interface.
Private Sub OPCode(variable1 As String, variable2 As String, variable3 As String, variable4 As String, variable5 As String)
Dim dtBeforeUpdate As New DataTable()
Dim dtAfterUpdate As New DataTable()
Using mysqlconn = New MySqlConnection("server=localhost;user id=root;password=1234;database=Share")
Using cmd As New MySqlCommand("SELECT Column4_Name FROM name_list;", mysqlconn)
mysqlconn.Open()
dtBeforeUpdate.Load(cmd.ExecuteReader)
mysqlconn.Close()
End Using
Using cmd As New MySqlCommand($"UPDATE Name_list Set Numerology = #Numerologh, FSTLetter = #FST, Timing = #Timing, P_Numerology = #P_Numerology WHERE Symbol = #sy ", mysqlconn)
cmd.Parameters.Add("#Numerology", MySqlDbType.String).Value = $"N-{variable1} S- {variable2}"
cmd.Parameters.Add("#FST", MySqlDbType.String).Value = variable3
cmd.Parameters.Add("#Timing", MySqlDbType.String).Value = variable4
cmd.Parameters.Add("#P_Numerology", MySqlDbType.String).Value = variable5
cmd.Parameters.Add("#sy", MySqlDbType.String)
mysqlconn.Open()
For Each row As DataRow In dtBeforeUpdate.Rows
cmd.Parameters("#sy").Value = row(0).ToString.Trim
cmd.ExecuteNonQuery()
Next
mysqlconn.Close()
End Using
Using cmd As New MySqlCommand("Select * From Name_list;", mysqlconn)
mysqlconn.Open()
dtAfterUpdate.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dtAfterUpdate
End Sub
Actually, I don't get it. It seems like you are updated the entire table with the same data. Do you expect the variable1, variable2 etc. to change somehow?
Don't know where your variable1, variable2, etc come from, but those look to be static, so your loop is somewhat pointless it would seem. You're updating every row in the loop to the exact same values (unless there's other code you're not showing), so just update the table without the loop:
Using con As New MySQLConnection
con.ConnectionString = "server=localhost;user id=root;password=1234;database=Share"
con.Open
Using cmd As New MySQLCommand
cmd.Connection = con
cmd.CommandText = "UPDATE Name_list Set Numerology = '" & "N-" & variable1 & " S- " & variable2 & "',FSTLetter = '" & variable3 & "',Timing = '" & vriable4 & "',P_Numerology = '" & variable5 & "'"
cmd.ExecuteNonQuery
End Using
End Using

Delete all data in MS Access database

Here is the code I am using :
Try
Dim SqlQuery As String = "DELETE FROM tblEXcel WHERE ID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record deleted..")
Catch ex As Exception
MsgBox(ex.Message, vbOKOnly, "Clear Measurement Table!")
End Try
For DataBindings you can use this...
Do While ExampleBindingSource.Count > 0
ExampleBindingSource.RemoveCurrent()
Loop
Remove WHERE ID = " & id. Then ALL the rows will be deleted.
So, simply change your SQL command to:
Dim SqlQuery As String = "DELETE FROM tblEXcel"
use below statement:
delete * from tblName
Dim SqlQuery As String = "DELETE * FROM tblEXcel WHERE ID = " & id & ";"
Dim MySQLCON As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=test;User ID=root;Password=mysql;")
Dim COMMAND As MySqlCommand
MySQLCON.Open() /Open your Connection
Dim DELETERECORD As String = "DELETE * FROM tblEXcel WHERE ID= #id"
COMMAND = New MySqlCommand(DELETERECORD, MySQLCON)
COMMAND.Parameters.AddWithValue("#id", userID.Text) /userID.Text is the string of the users ID
COMMAND.ExecuteNonQuery()
MySQLCON.Close() /Always Close your Connection
MySQLCON.Dispose() /Always Dispose of your Connection
Note:
The way you where doing it was vulnerable to MySQL Injection Attacks. If you have a lot of MySQL Code in your application, i advise you to rewrite it in the way so it is not vulnerable.

sql command query for log in asp.net

Hello i been looking around and i cant seem to find how to make a safe sql command ( vs injections ) for checking log in details from the database , i found something like this code which seem to be the thing i need but i cant seem to understand how to actully check if the user exists.
This code happens on LogIn Button click , and i am suppose to redirect the user to another page + save some of the valuse from the row ( like userId , companyId and few others ) into sessions for later use . I just not so sure how .
Protected Sub enterBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
Dim query As String = String.Format("select userName, userPassword, companyId from " & "[users] where userName like '%+#userName+%', userBox.Text)
Using con As New SqlConnection(connectionString)
'
' Open the SqlConnection.
'
con.Open()
'
' The following code uses an SqlCommand based on the SqlConnection.
'
Using da As New SqlDataAdapter()
Using command As New SqlCommand(query, con)
'pass the parameter
command.Parameters.Add(New SqlParameter("#userName", userBox.Text))
command.Parameters.Add(New SqlParameter("#userPassword", passwordInput.Text))
command.Parameters.Add(New SqlParameter("#companyId", companyIdBox.Text))
Dim ds As New DataSet()
da.SelectCommand = command
da.Fill(ds, "test")
End Using
End Using
End Using
Change your query string to
Dim query As String = "select userName, userPassword, companyId " & _
"from [users] " & _
"where userName like #userName " & _
"userPassword = #userPassword " & _
"companyID = #companyID"
and then in the section where you add the parameters
command.Parameters.Add(New SqlParameter("#userName", "%" & userBox.Text "%"))
The trick is to write the query text as clean as possible and add the wildcard required by the like directly in the value passed to the SqlParameter constructor
I suggest also to use a different way to build your Parameters collection
command.Parameters.Add(New SqlParameter With
{
.ParameterName = "#userName",
.Value = "%" & userBox.Text "%",
.SqlDbType = SqlDbType.NVarChar
})
This is more verbose but avoids the confusion between the two overloads of the Add method the one that accepts an SqlDbType and the one that accepts an object as second parameter.
Then if you want to know if a user with that name, password an company has been found just loop at the count of rows present in the first table of the DataSet
If ds.Tables(0).Rows.Count > 0 then
... you have your user .....
End if
However a better query would be
Dim query As String = "IF EXISTS(select 1 from [users] " & _
"where userName like #userName " & _
"userPassword = #userPassword " & _
"companyID = #companyID) " & _
"SELECT 1 ELSE SELECT 0"
and instead of the SqlDataAdapter and DataSet you write simply
Using con As New SqlConnection(connectionString)
Using command As New SqlCommand(query, con)
con.Open()
command.Parameters.Add(New SqlParameter("#userName", userBox.Text))
command.Parameters.Add(New SqlParameter("#userPassword", passwordInput.Text))
command.Parameters.Add(New SqlParameter("#companyId", companyIdBox.Text))
Dim userExists = Convert.ToInt32(command.ExecuteScalar())
if userExists = 1 Then
Session["UserValidated"] = "Yes"
else
Session["UserValidated"] = "No"
End If
End Using
End Using