The sequence is not correct when using insert into function in VBA - vb.net

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 & "',' .."

Related

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

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

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.)

"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.

SYNTAX ERROR INSERT INTO STATEMENT Visual Basic

Why am I getting this error
Syntax error INSERT INTO statement
Please help! Thanks in advance!
Dim cmd As New OleDb.OleDbCommand
If TabControl1.SelectedIndex = 0 Then
If Not cnn.State = ConnectionState.Open Then
'open connection if it is not yet open
cnn.Open()
End If
cmd.Connection = cnn
'check whether add new or update
If Me.txtStdID.Tag & "" = "" Then
'add new
'add data to table
cmd.CommandText = "INSERT INTO Student (StudentID, LastName, FirstName, MiddleInitial, Grade, Section, ContactNumber, AdviserID, CounselorID, ParentName)" & _
"VALUES('" & Me.txtStdID.Text & "','" & Me.txtLname.Text & "','" & _
Me.txtFname.Text & "','" & Me.txtMidInt.Text & "','" & _
Me.txtGrade.Text & "','" & Me.txtSection.Text & "','" & Me.txtContact.Text & "','" & _
Me.txtAdvID.Text & "','" & Me.txtConID.Text & "','" & Me.txtPname.Text & "')"
cmd.ExecuteNonQuery()
Well, this is a well known problem. Databases define many words as "reserved keywords", and if they are used for column names or table names, they need to be enclosed in the appropriate quoting character for your database.
Seeing that you are using an OleDbConnection I assume that you are using MS-Access as database. In that case the list of reserved keywords could be found here,
And indeed SECTION is a reserved keyword, so your query, should be written as
"INSERT INTO Student (......, [Section], ......
Said that, let's say something about string concatenation to build an SQL Query.
It's bad, bad, bad.... There are numerous problem with that. For example, what happens if one of your fields contains a single quote? The whole query will fail again with a Syntax error. Also, albeit more difficult to exploit with Access because it doesn't support multiple command texts there is the problem of SQL Injection to avoid at all costs. You need to learn how to use a PARAMETERIZED QUERY
Dim sqlText = "INSERT INTO Student (StudentID, LastName, FirstName, " & _
"MiddleInitial, Grade, [Section], ContactNumber, AdviserID, " & _
"CounselorID, ParentName) VALUES (?,?,?,?,?,?,?,?,?,?)"
If TabControl1.SelectedIndex = 0 Then
Using cnn = New OleDbConnection(...constring here....)
Using cmd = new OleDbCommand(sqlText, cnn)
cnn.Open()
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = Me.txtStdID.Text
cmd.Parameters.Add("#p2", OleDbType.VarWChar).Value = Me.txtLname.Text
.... and so on with the other parameters ....
.... strictly following the order of the fields in the insert....
cmd.ExecuteNonQuery()
End Using
End Using

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