VB.Net 2013 (VB fail to search the access database) - sql

I have this weird problem when I register using my system I developed in VB.NET, it does not allow me to login(in the login form) using the correct username and password I registered. However, when I manually input the username and password inside the Access database, I manage to login without any problem. Here are the codes of my login and register
Login
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\lenovo\Documents\Visual Studio 2012\Projects\SDP user interface\SDP user interface\bin\Debug\SCPdatabase.accdb")
conn.Open()
sql = "Select * FROM Members WHERE Username ='" & txtusername.Text & "' AND [Password] ='" & txtpassword.Text & " ' "
cmd = New OleDbCommand(sql, conn)
dr = cmd.ExecuteReader()
If dr.HasRows Then
MessageBox.Show("Login Success")
Me.Hide()
Member_Page.Show()
Member_Page.lblwelcome.Text = "Welcome" & txtusername.Text
Else
MessageBox.Show("Login Failed")
End If
dr.Close()
conn.Close()
Register
Dim flag As Integer
MyConn.Open()
sql = "Insert INTO Members (Username,[IC],Email,PhoneNumber,FullName,[Password],Newsletter) values (' " & txtusername3.Text & "','" & txtic3.Text & "','" & txtemail3.Text & "','" & txtphone3.Text & "','" & txtname3.Text & "', ' " & txtpwd3.Text & " ',' " & cmb3.Text & " ')"
cmd = New OleDbCommand(sql, MyConn)
flag = cmd.ExecuteNonQuery()
If flag > 0 Then
MessageBox.Show(flag & " records added", "Add Records Successful", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
MyConn.Close() 'closes the connection
Please advice thnx

Your INSERT statement is adding whitespace characters to the values:
' " & txtusername3.Text & "'
^--- here
and
' " & txtpwd3.Text & " '
^--- here ^--- here
etc.
But then when you select from the table, you don't include them:
WHERE Username ='" & txtusername.Text & "' AND [Password] ='" & txtpassword.Text & " '
just here ---^
Get rid of the whitespace characters entirely, as they're changing the values from what you expect those values to be.
Or, better yet, use query parameters so you don't have to manually build these string values in the first place. (And, as a bonus, would close the enormous SQL injection vulnerability you currently have.)

Related

The sequence is not correct when using insert into function in VBA

Got a question here, the code works nicely no error at all, but when I add record to access the sequence just got wrong. Please refer to the image(https://i.stack.imgur.com/uncf4.png), the record of John Doe, the User_ID weirdly fall under user_name, user_IC fall to user_ID and also user_name fall to user_IC. Is there any error in my code? I have change the sequence after VALUES but still the same.
Try
con.Open()
cmd = New OleDb.OleDbCommand("INSERT INTO [user biodata] VALUES('" & User_nameTextBox.Text & "','" & User_IDTextBox.Text & "','" & User_ICTextBox.Text & "','" & User_genderTextBox.Text & "','" & User_phoneTextBox.Text & "','" & User_stateTextBox.Text & "','" & User_pwTextBox.Text & "')", con)
If (User_ICTextBox.Text = "" And User_nameTextBox.Text = "" And User_genderTextBox.Text = "" And User_phoneTextBox.Text = "" And User_stateTextBox.Text = "" And User_IDTextBox.Text = "" And User_pwTextBox.Text = "") Then
MessageBox.Show("Please enter the details")
Else
cmd.ExecuteNonQuery()
MsgBox("Succerssfully Registered. You can login now!", MsgBoxStyle.Information, "Success")
Me.Close()
Form1.Show()
User_ICTextBox.Clear()
User_nameTextBox.Clear()
User_genderTextBox.Clear()
User_phoneTextBox.Clear()
User_stateTextBox.Clear()
User_IDTextBox.Clear()
User_pwTextBox.Clear()
End If
con.Close()
Catch ex As Exception
MsgBox("Error")
User_ICTextBox.Clear()
User_nameTextBox.Clear()
User_genderTextBox.Clear()
User_phoneTextBox.Clear()
User_stateTextBox.Clear()
User_IDTextBox.Clear()
User_pwTextBox.Clear()
End Try
Either modify your code completely to parameters, or specify the order of the field names:
"INSERT INTO [user biodata] ([Field1], [Field2] .. [FieldN]) VALUES('" & User_nameTextBox.Text & "',' .."

Using case-sensitive SELECT query for login module

I am developing a Windows Form application using vb.net in VS10 with user management. I am using following code when a user tries to login:
Try
Dim sel As String
sel = "SELECT uid, name, loginid, password, type FROM user_master WHERE loginid = '" & UsernameTextBox.Text & "' AND password = '" & PasswordTextBox.Text & "'"
Dim cnn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\RSMS_DB.mdf;Integrated Security=True;User Instance=True")
Dim da As New SqlDataAdapter(sel, cnn)
Dim ds As New DataSet()
da.Fill(ds)
If ds.Tables(0).Rows.Count = 0 Then
MsgBox("Wrong Username and Password Combination!", MsgBoxStyle.Critical, "Login Failed")
Else
current_uid = ds.Tables(0).Rows(0)(0)
current_name = ds.Tables(0).Rows(0)(1)
current_loginid = ds.Tables(0).Rows(0)(2)
current_password = ds.Tables(0).Rows(0)(3)
current_type = ds.Tables(0).Rows(0)(4)
MsgBox("Welcome '" & ds.Tables(0).Rows(0)(1) & "'!", MsgBoxStyle.OkOnly, "Login Successful")
Dim upd = "UPDATE user_master SET lastlogin = '" & System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") & "' WHERE uid = " & current_uid & ""
Dim cmd As New SqlCommand(upd, cnn)
cnn.Open()
cmd.ExecuteNonQuery()
If checkboxLoginState.Checked = True Then
cmd.CommandText = "INSERT INTO login_state VALUES('" & current_uid & "', '" & current_name & "', '" & current_loginid & "', '" & current_password & "', '" & current_type & "')"
cmd.ExecuteNonQuery()
End If
cnn.Close()
load_user_permissions(current_uid) 'DISABLING OPTIONS ACCORDING TO USER RIGHTS
Me.Close()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Database Error")
End Try
All I want to ask is if it is the right method? Is the SELECT Query case sensitive by default?
The SQL Keywords are case-insensitive (SELECT, FROM, WHERE, etc), but are often written in all caps. However in some setups table and column names are case-sensitive. Usually case-sensitive table and column names are the default. If you want to change it then you can change it in a function of the database's collation settings.
Source - And this could also be helpful for you.
If security is important to you then you should hash the passwords - do not save passwords as plain text! You should check out the library libsodium

"variable" is not declared error

Image of the error
I am new to Vb.net programing and I need a little help here, I pretend to send info to my database, the first query gives me the id I need and I declare it as "postoid", when I later try to call it (in the insert into part) it says it is not declared, I have googled the problem a hundred times but I couldn't find the answer.
Ps: this code is all in the same private sub
Try
mysqlconn.Open()
queryrow = "Select * from postos where postos_nome ='" & TextBox1.Text & "'"
COMMANDuser1 = New MySqlCommand(queryrow, mysqlconn)
READERuser = COMMANDuser1.ExecuteReader
While READERuser.Read
Dim postoid = READERuser.GetString("postos_id")
End While
mysqlconn.Close()
Catch ex As Exception
End Try
Dim sqlquery As String = "INSERT INTO computadores VALUES (0,'" & pcname.ToUpper & "','" & ip & "','" & so & "','" & cpu & "','" & ram & "','" & gc & "','" & wserial & "','" & mnome & "','" & mserial & "','" & "--- ,,'Inativo','" & empresaid & "','" & postoid & "','" & userid & "')"
Dim sqlcommand As New MySqlCommand
With sqlcommand
.CommandText = sqlquery
.Connection = mysqlconn
.ExecuteNonQuery()
End With
MsgBox("Computador Adicionado")
Dispose()
Close()
Your variable postoid is out-of-scope outside the block it is declared in.
All you need to do is declare it outside the Try structure:
Dim postoid As String = ""
queryrow = "Select postos_id from postos where postos_nome = #PostosNome"
Using COMMANDuser1 As New MySqlCommand(queryrow, mysqlconn)
COMMANDuser1.Parameters.Add("#PostosNome", TextBox1.Text)
mysqlconn.Open()
READERuser = COMMANDuser1.ExecuteReader()
While READERuser.Read
postoid = READERuser.GetString("postos_id")
End While
mysqlconn.Close()
End Using
If postoid <> "" Then
' perform the insert...
I did not actually use Try in that, as you have no code in your Catch block - having no code in the Catch block has the effect of hiding errors. You want to see the errors.
For using SQL parameters, see, e.g., Inserting data into a MySQL table using VB.NET but please use .Add instead of .AddWithValue - the latter will not always work as intended.

data is not inserted to database

i tried to insert the data into database with this code
Public Sub AddUser()
Dim con As dbConn = New dbConn()
Dim SqlSelect As String
SqlSelect = "SELECT * FROM login Where user_id='" & WorkerID_.Text & "'"
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
Dim reader As OleDbDataReader
Dim da As New OleDbDataAdapter
con.open()
reader = cmd.ExecuteReader()
reader.Read()
If reader.HasRows() Then
reader.Close()
con.close()
FailureText.Text = "User ID already exists!"
Else
reader.Close()
con.close()
Dim InsertSQL As String
InsertSQL = "INSERT INTO login (user_id, user_role, user_password, user_status) VALUES "
InsertSQL &= "('" & WorkerID_.Text & "', "
InsertSQL &= "'Worker', "
InsertSQL &= "'12345', 1)"
Dim SqlUpdate As String
SqlUpdate = "INSERT INTO Worker (ID, WorkerID, WorkerName, DoB, Address, Phone, Email, CompanyName, PassportNum, PassportExp, VisaExp, VisaStatus, user_id) VALUES (default,"
SqlUpdate &= "'" & WorkerID_.Text & "', "
SqlUpdate &= "'" & WorkerName.Text & "', "
SqlUpdate &= "'" & DoB.Text & "', "
SqlUpdate &= "'" & Address.Text & "', "
SqlUpdate &= "'" & Phone.Text & "', "
SqlUpdate &= "'" & Email.Text & "', "
SqlUpdate &= "'" & Company.SelectedValue & "', "
SqlUpdate &= "'" & PassNum.Text & "', "
SqlUpdate &= "'" & PassExp.Text & "', "
SqlUpdate &= "'" & VisaExp.Text & "', "
SqlUpdate &= "'No Visa', "
SqlUpdate &= "'" & WorkerID_.Text & "') "
Dim insertCommand As New OleDbCommand(SqlUpdate, con.oleconnection)
Dim cmd1 As New OleDbCommand(InsertSQL, con.oleconnection)
Try
con.open()
cmd1.ExecuteNonQuery()
insertCommand.ExecuteNonQuery()
Catch
FailureText.Text = "Unable to add user"
Finally
con.close()
End Try
End If
Response.Redirect("Workers.aspx")
End Sub
the Insert into login part is working. the data is well inserted. but for the insert into worker part is not working. the data is not inserted into the table. the program shows no error and it still can work. what could possibly wrong with this?
Read another answer on OleDb I just answered on another post. You will be wide open to sql-injection too. Parmaeterize queries. By you concatenating strings to build one command, what if one value has a single-quote within the text entry. You are now hosed. What if someone puts malicious SQL commands and then deletes your records or entire table(s). Learn to parameterize your queries and also clean values, especially if coming from a web interface.
Your commands should probably be updated something like
Dim con As dbConn = New dbConn()
Dim SqlSelect As String
SqlSelect = "SELECT * FROM login Where user_id= #parmUserID"
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
cmd.Parameters.AddWithValue( "parmUserID", WorkerID_.Text )
Follow-suit with the Insert and update commands... parameterize them but using #variable place-holders in your commands.
Dim InsertSQL As String
InsertSQL = "INSERT INTO login (user_id, user_role, user_password, user_status) "
InsertSQL &= " VALUES ( #parmUser, #parmRole, #parmPwd, #parmStatus )"
Dim cmdInsert As New OleDbCommand(InsertSQL, con.oleconnection)
cmdInsert.Parameters.AddWithValue( "parmUser", WorkerID_.Text )
cmdInsert.Parameters.AddWithValue( "parmRole", "Worker" )
cmdInsert.Parameters.AddWithValue( "parmPwd", "12345" )
cmdInsert.Parameters.AddWithValue( "parmStatus", 1 )
Dim SqlUpdate As String
SqlUpdate = "INSERT INTO Worker (ID, WorkerID, WorkerName, DoB, Address, Phone, Email, CompanyName, PassportNum, PassportExp, VisaExp, VisaStatus, user_id) "
SqlUpdate &= " VALUES ( #parmID, #parmName, #parmDoB, etc... ) "
Dim cmdUpdate As New OleDbCommand(SqlUpdate, con.oleconnection)
cmdUpdate.Parameters.AddWithValue( "parmID", WorkerID_.Text )
cmdUpdate.Parameters.AddWithValue( "parmName", WorkerName.Text )
cmdUpdate.Parameters.AddWithValue( "parmDoB", DoB.Text )
-- etc with the rest of the parameters.
Final note. Make sure the data types you are trying to insert or update are of same type expected in the table. Such example is your "Birth Date" (DoB) field. If you are trying to insert as simple text, and it is not in an auto-converted format, the SQL-Insert might choke on it and fail. If you have a textbox bound to a DateTime type, then your parameter might be Dob.SelectedDate (such as a calendar control), or you could pre-convert from text to a datetime and then use THAT as your parameter value.
Other numeric values, leave as they are too, they should directly apply for the insert. You could also identify the AddWithValue() call the data type the parameter should represent (string, int, double, datetime, whatever)
You seem to have 12 parameters you wish to insert, and 13 arguments in the VALUES part of your insert query. is the Default seen in the values section below intentional?
INSERT INTO Worker (ID, ... VisaStatus) VALUES (default,"
ensure you have the correct number of parameters defined and added, then let us know, but i could be missing something else.

SQL command will not insert into database

I'm trying to use a VB button to insert data into a database, but it keeps bringing up the error message I have in place for exceptions.
Can anyone help me with why this does not update the database?
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sql As String
Dim adapter As New SqlDataAdapter
Dim Customer As String = TextBox1.Text
Dim Product As String = TextBox2.Text
Dim Location As String = TextBox3.Text
Dim Details As String = TextBox4.Text
Dim Owners As String = DropDownList1.Text
Dim Urgency As String = DropDownList2.Text
connetionString = "Data Source=ZUK55APP02;Initial Catalog=BugFixPortal;User ID=SLC***;Password=rep***"
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand
adapter.UpdateCommand.CommandText = sql
adapter.UpdateCommand.ExecuteNonQuery()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
End Sub
I would not go down this road as your code is weak against SQL Injection
you should use parameters instead.Something like the below
c.Open();
string insertString = #"insert into YourTable(name, street, city,....) values(#par1, #par2, #parN,....)"
SqlCommand cmd = new SqlCeCommand(insertString, c);
cmd.Parameters.Add("#par1", SqlDbType.VarChar).Value = "MyName";
//etc
cmd.ExecuteNonQuery();
c.Close();
You are incorrectly quoting your values.
This string has an opening and closing single quote around ALL the values, which is incorrect.
VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
Instead, put single quotes around character data, eg., if Product is a varchar, it would look like this:
VALUES (" & Owners & ", " & Customer & ", '" & Product & "', " & Location & ", " & Urgency & ", " & Details & ")"
The real problem, though, is that you should be using parameterized queries instead. This code is prone to SQL injection attacks.
Change this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
to Something like this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!" & ex.Message)
It will give you more details on the exception, however at a quick glance I can see a problem, the values you are trying to insert are strings, you've enclosed all your values in a single set of ' characters, rather than enclosing each string parameter in a pair of ' values, i.e.
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & "', '" & Customer & "', '" & Product & "',' " & Location & "', '" & Urgency & "', '" & Details & "')"
You really should look at parameterizing your queries as you're wide open to SQL injection attacks. See HERE
In terms of your code itself, your SQL syntax is wrong as you need to put apostrophes around each value. Try this:
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('" & Owners & "', '" & Customer & "', '" & Product &
"', '" & Location & "', '" & Urgency & "', '" & Details & "')"
Here's an example using Parameters
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('#Owners', '#Customer', '#Product', '#Location', '#Urgency', '#Details')"
Then add parameters like so:
command.Parameters.AddWithValue("#Owners", Owners)
command.Parameters.AddWithValue("#Customer", Customer)
command.Parameters.AddWithValue("#Product", Product)
command.Parameters.AddWithValue("#Location", Location)
command.Parameters.AddWithValue("#Urgency", Urgency)
command.Parameters.AddWithValue("#Details", Details)
I think you want to use adapter.InsertCommand instead of adapter.UpdateCommand
in
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand //(adapter.InsertCommand)
adapter.UpdateCommand.CommandText = sql //(adapter.InsertCommand)
adapter.UpdateCommand.ExecuteNonQuery() //(adapter.InsertCommand)
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
and agree with parametrized sql query
see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx for more infos