Storing ID from SQL result - sql

Im running the following code to tell if a user excists on a database - standard stuff. Obviously once the code is run a boolean true or false will be returned if there is a result. If a result is found i want to store the ID of the said result. Can anyone tell me how'd id go about doing this?
code:
Username = txtUserName.Text
Password = txtPassword.Text
dbConnInfo = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Dave\Documents\techs.mdb"
con.ConnectionString = dbConnInfo
con.Open()
Sql = "SELECT * FROM techs WHERE userName = '" & Username & "' AND '" & Password & "'"
LoginCommand = New OleDb.OleDbCommand(Sql, con)
CheckResults = LoginCommand.ExecuteReader
RowsFound = CheckResults.HasRows
con.Close()
If RowsFound = True Then
MsgBox("Details found")
TechScreen.Show()
Else
MsgBox("Incorrect details")
End If

There are a lot of problems with the code snippet you posted. Hopefully, I can help you correct these problems.
In order to load the ID of the result you'll want to use SqlCommand.ExecuteScalar() as this is optimized to pull back one result from Sql.
As to what is wrong with your code, you're wide open to Sql Injection attacks and you should be using Parametrized Queries as shown in my sample below.
Public Function AddProductCategory( _
ByVal newName As String, ByVal connString As String) As Integer
Dim newProdID As Int32 = 0
Dim sql As String = _
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); " _
& "SELECT CAST(scope_identity() AS int);"
Using conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar)
cmd.Parameters("#Name").Value = newName
Try
conn.Open()
newProdID = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
Return newProdID
End Function
Source: MSDN

Related

Can't INSERT INTO access database

I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.
Code:
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()
I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database? I can insert this query by running query directly in Access.
Firstly I would check the database settings. If your app copies a new copy of the database each time you run it that would explain why you can select existing data and why your new data is not being saved (Well it is being saved, but the database keeps getting replaced with the old one). Rather set it up to COPY IF NEWER.
Further, you should ALWAYS use parameterized queries to protect your data. It is also is less error prone than string concatenated commands ans is much easier to debug.
Also, I recommend using a USING block to handle database connections so that your code automatically disposes of resources no longer needed, just in case you forget to dispose of your connection when you are done. Here is an example:
Using con As New OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = "
Dim sql_insert As String = "INSERT INTO Tbl (Code) " & _
"VALUES " & _
"(#code);"
Dim sql_insert_entry As New OleDbCommand
con.Open()
With sql_insert_entry
.Parameters.AddWithValue("#code", txtCode.Text)
.CommandText = sql_insert
.Connection = con
.ExecuteNonQuery()
End With
con.Close()
End Using
Here is an example where data operations are in a separate class from form code.
Calling from a form
Dim ops As New Operations1
Dim newIdentifier As Integer = 0
If ops.AddNewRow("O'brien and company", "Jim O'brien", newIdentifier) Then
MessageBox.Show($"New Id for Jim {newIdentifier}")
End If
Back-end class where the new primary key is set for the last argument to AddNewRow which can be used if AddNewRow returns true.
Public Class Operations1
Private Builder As New OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
}
Public Function AddNewRow(
ByVal CompanyName As String,
ByVal ContactName As String,
ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName) VALUES (#CompanyName, #ContactName)"
cmd.Parameters.AddWithValue("#CompanyName", CompanyName)
cmd.Parameters.AddWithValue("#ContactName", ContactName)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
Success = True
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
End Class

MysqlDataReader.Read stuck on the last record and doesnt EOF

i confused why mySqlDataReader.Read stuck on the last record and doesnt EOF ..
Here's my private function for executeSql :
Private Function executeSQL(ByVal str As String, ByVal connString As String, ByVal returnRecordSet As Boolean) As Object
Dim cmd As Object
Dim objConn As Object
Try
If dbType = 2 Then
cmd = New MySqlCommand
objConn = New MySqlConnection(connString)
Else
cmd = New OleDbCommand
objConn = New OleDbConnection(connString)
End If
'If objConn.State = ConnectionState.Open Then objConn.Close()
objConn.Open()
cmd.Connection = objConn
cmd.CommandType = CommandType.Text
cmd.CommandText = str
If returnRecordSet Then
executeSQL = cmd.ExecuteReader()
executeSQL.Read()
Else
cmd.ExecuteNonQuery()
executeSQL = Nothing
End If
Catch ex As Exception
MsgBox(Err.Description & " #ExecuteSQL", MsgBoxStyle.Critical, "ExecuteSQL")
End Try
End Function
And this is my sub to call it where the error occurs :
Using admsDB As MySqlConnection = New MySqlConnection("server=" & rs("server") & ";uid=" & rs("user") & ";password=" & rs("pwd") & ";port=" & rs("port") & ";database=adms_db;")
admsDB.Open()
connDef.Close()
rs.Close()
'get record on admsdb
Dim logDate As DateTime
Dim str As String
str = "select userid, checktime from adms_db.checkinout in_out where userid not in (select userid " &
"from adms_db.checkinout in_out join (select str_to_date(datetime,'%d/%m/%Y %H:%i:%s') tgl, fid from zsoft_bkd_padang.ta_log) ta " &
"on ta.fid=userid and tgl=checktime)"
Dim rsAdms As MySqlDataReader = executeSQL(str, admsDB.ConnectionString, True)
Dim i As Integer
'This is where the error is, datareader stuck on the last record and doesnt EOF
While rsAdms.HasRows
'i = i + 1
logDate = rsAdms(1)
'save to ta_log
str = "insert into ta_log (fid, Tanggal_Log, jam_Log, Datetime) values ('" & rsAdms(0) & "','" & Format(logDate.Date, "dd/MM/yyyy") & "', '" & logDate.ToString("hh:mm:ss") & "', '" & logDate & "')"
executeSQL(str, oConn.ConnectionString, False)
rsAdms.Read()
End While
'del record on admsdb
str = "truncate table checkinout"
executeSQL(str, admsDB.ConnectionString, False)
End Using
i'm new to vbnet and really have a little knowledge about it,, please help me,, and thank you in advance..
The issue is that you're using the HasRows property as your loop termination expression. The value of that property never changes. Either the reader has rows or it doesn't. It's not a check of whether it has rows left to read, so reading has no effect.
You are supposed to use the Read method as your flag. The data reader begins without a row loaded. Each time you call Read, it will load the next row and return True or, if there are no more rows to read, it returns False.
You normally only use HasRows if you want to do something special when the result set is empty, e.g.
If myDataReader.HasRows Then
'...
Else
MessageBox.Show("No matches found")
End If
If you don't want to treat an empty result set as a special case then simply call Read:
While myDataReader.Read()
Dim firstFieldValue = myDataReader(0)
'...
End While
Note that trying to access any data before calling Read will throw an exception.

LogIn form with user and admin using VB.net and Mysql

I want to get the privilege if it's admin or encoder but with this code I can't get any value... this is my code please help me
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
cn = New MySqlConnection
cn.ConnectionString = "server=localhost; userid=root; database=dp_inventory;"
Dim reader As MySqlDataReader
Try
cn.Open()
Dim sql As String
sql = "Select from dp_inventory.user_account where employeeID='" & UsernameTextBox.Text & "' and password='" & PasswordTextBox.Text & "' "
cmd = New MySqlCommand(sql, cn)
reader = cmd.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
Dim users As String
users = "select privilege from user_account where employeeID='" & UsernameTextBox.Text & "'"
If count = 1 Then
If users = "admin" Then
frmAdminMain.Show()
ElseIf users = "encoder" Then
MainForm.Show()
End If
ElseIf count > 1 Then
frmAdminMain.Show()
Else
MsgBox("tryy again")
End If
Catch ex As Exception
MsgBox("Try again")
End Try
End Sub
There are quite a few errors in this code you wrote. Your first issue is you are simply trying to count without actually using a Sql counter.
Take a look at a code snippet from one of my applications here for a general idea
SelectStr = "SELECT MagPieces_Number,MagOperators_Number,MagFactor_Number,MagTotal_Number" & _
" FROM Parts_Mag WHERE Quote_Number_Id = #QuoteId and Quote_Rev_Id = #RevId and Part_Number_Id = #PartID and Part_Numeral_Id = #PartNumeral and SiteLocation = #Site"
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#QuoteId", QuoteId)
SqlDataCmd.Parameters.AddWithValue("#RevId", RevId)
SqlDataCmd.Parameters.AddWithValue("#PartId", PartNumber)
SqlDataCmd.Parameters.AddWithValue("#PartNumeral", PartNumeral)
SqlDataCmd.Parameters.AddWithValue("#Site", SiteLocation)
SqlReader = SqlDataCmd.ExecuteReader
While SqlReader.Read
MagPieces = SqlReader("MagPieces_Number").ToString
MagOperators = SqlReader("MagOperators_Number").ToString
MagFactor = SqlReader("MagFactor_Number").ToString
MagTotal = SqlReader("MagTotal_Number").ToString
End While
MagParticle.txtPiecesPerHour.Text = MagPieces
MagParticle.txtOperators.Text = MagOperators
MagParticle.txtMatFactor.Text = MagFactor
MagParticle.labMagTotal.Text = MagTotal
Catch ex As Exception
ErrorMessage(ex.message)
SqlReader.Close()
End Try
SqlReader.Close()
If you are simply looking for if your select statement has "Admin" or "Encoder" at the end, it would simply be something like this:
Dim empId as String = UsernameTextbox.Text
Dim SelectStr as String = "Select privilege from dp_inventory.user_account where employeeID=#empId
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#empId", empId)
Then read it with a reader. Once you have the general idea you should be able to take it from there! Im not quite sure why you need the count to begin with so you may want to just negate that portion out and simply read from your table based on the ID

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

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