How to add Data into the Database from VB.Net - vb.net

I'm new to VB. It's been few weeks since I started learning VB.My question is I'm having difficulty in adding Data in to the Database (I'm using MS Access) from VB. So far I got this code but it isn't running well:
Imports System.Data.OleDb
Public Class CraeteAccount
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim cmd As New OleDbCommand
Dim dr As OleDbDataReader
Public Sub btnCreate_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & IO.Path.Combine(My.Application.Info.DirectoryPath, "LogIn1.accdb")
Dim cmd As New OleDbCommand
Dim cnn As OleDbConnection = New OleDbConnection(connString)
Dim str As String
Dim UserName As String
Dim Password As String
If txtPassword.Text = txtRetype.Text Then
cnn.Open()
Try
UserName = txtUserName.Text
Password = txtPassword.Text
str = "UPDATE Users SET UserName= '" & UserName & "', Password= '" & Password
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#UserName", UserName)
cmd.Parameters.AddWithValue("#Password", Password)
cmd.ExecuteNonQuery()
MsgBox("New User has been Created!")
cnn.Close()
Me.Hide()
Catch ex As Exception
MsgBox("Error Occured!")
cnn.Close()
End Try
Me.Close()
Else
MsgBox("Check your Password!")
cnn.Close()
txtPassword.Focus()
End If
End Sub
When the code runs It donot add data and quickly goes to catch to show the Message Box which reads "Error Occured". So Can anyone Please Help me?

At a quick glance, the SQL query is broken in several ways:
str = "UPDATE Users SET UserName= '" & UserName & "', Password= '" & Password
The first thing to notice is that you're not closing the quotes after the password. However, even that isn't what you really want to do. What you want to do is this:
str = "UPDATE Users SET UserName=#UserName, Password=#Password"
This creates query parameters, which your next two lines are looking to populate with values:
cmd.Parameters.AddWithValue("#UserName", UserName)
cmd.Parameters.AddWithValue("#Password", Password)
Putting user values directly into the query is called a SQL injection vulnerability. It allows users to execute arbitrary code on your database, which is clearly a bad thing. So you're definitely going to want to stick with using these parameters instead.
The second problem here is that this query is going to update every record int he table. So it's basically going to overwrite all Users records with multiple copies of this one record.
If this really should be an UPDATE statement when you're going to want to add a WHERE clause to it which would identify the specific record you want to update.
However, I suspect based on the context that this should instead be an INSERT statement, since it's creating a new record:
str = "INSERT INTO Users (UserName, Password) VALUES (#UserName, #Password)"
Additionally, and this is important, you are storing user passwords in plain text. This is grossly irresponsible to your users. You should be obscuring user passwords with a 1-way hash so that they can never be retrieved in their original form. Not even by you as the system administrator.
(The language and emphasis used here may be a bit harsh for a beginner. Especially if you're working on a purely academic project with no actual users. But it's seriously that important. And there's no time like the present to learn about it.)
Another issue here is that you're assuming success of the query:
cmd.ExecuteNonQuery()
MsgBox("New User has been Created!")
At the very least you should be checking the return value to make sure a record was actually affected:
Dim rowsAffected As Int32 = cmd.ExecuteNonQuery()
If rowsAffected > 0 Then
MsgBox("New User has been Created!")
Else
'no record was inserted, handle error condition
End If
Another issue that you're facing, which isn't directly related to your problem but is making it much more difficult for you to debug your problem, is that you're ignoring error information:
Catch ex As Exception
MsgBox("Error Occured!")
cnn.Close()
In this code block the ex variable contains all of the information that the .NET Framework can give you about the error that took place. What you're basically doing is replacing all of that diagnostic information (error message, stack trace, etc.) with a single custom error message that contains no information.
Best not to do that.
Note that, given these issues, there may very well be other problems with the code. But this should at least get you going for a bit.

You're simultaneously trying to concatenate an update statement with user input (bad) and using parameterized values (good). Try
str = "UPDATE Users SET UserName=#UserName, Password=#Password"
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#UserName", UserName)
cmd.Parameters.AddWithValue("#Password", Password)
But this still won't work because this update statement will update all the records in the database with these values. Are you trying to update an existing record or create a new one? If you're updating an existing one, you need a WHERE clause; if you're trying to create a new one, you need to use INSERT instead.

Related

Deleting SQL datarow from a table swipes position of first and second row in vb.net

adding updating everything is fine even delete command is working but the strange part is after executing del command from vb.net application it swipes the position of EMPLOYEE_IDAND NAMEit shows normally in datagridviewafter adding or updating but specifically after deleting the record position of these to column changes until I stop the application and re run the entire project for debugging
Dim con As New MySqlConnection("server=localhost; user=root; password=Masoom1; database=airtech_db; convert zero datetime=true;")
Dim cmd As New MySqlCommand
Dim dt As New DataTable
Dim da As New MySqlDataAdapter
Dim sql As String
Dim DR As MySqlDataReader
Dim SQL_CMD_TXT As String
SQL_CMD_TXT = "DELETE FROM `employees` WHERE (`EMPLOYEE_ID` ='" &
EMPLOYEE_DEL_FRM.DEL_ID_TXT.Text & "'); SELECT * FROM `employees`;"
EMPLOYEE_DEL_FRM.Controls.Add(OBJECT_DATAGRIDVIEW)
With OBJECT_DATAGRIDVIEW
.Size = New Size(587, 242)
.Location = New Size(221, 171)
End With
Try
'DB CMD EXECUTION
con.Open()
With cmd
sql = SQL_CMD_TXT
.Connection = con
.CommandText = sql
End With
da.SelectCommand = cmd
da.Fill(dt)
'Command for datagridview object
With OBJECT_DATAGRIDVIEW
.DataSource = dt
'Scroll to the last row.
.Name = "MYDATAGRIDVIEW"
.FirstDisplayedScrollingRowIndex = .RowCount - 1
End With
con.Close()
Catch ex As Exception
Dim MEB = MessageBox.Show("ERROR FOR SQL CMD EXECUTION SECTION-" & ex.Message,
"SQL CMD EXECUTION", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End Try
attaching the normal and after delete result in images
enter image description here
I am not sure I completely understood your problem, but your problem could that the datagridview generates the columns automatically. See: DataGridView.AutoGenerateColumns
Instead of doing SELECT * FROM is would better to select just the fields you need. If you add more fields to your table in the future, the columns in the datagridview may be displaced because they are in no particular order.
Rather than add the datagridview to your form at runtime:
EMPLOYEE_DEL_FRM.Controls.Add(OBJECT_DATAGRIDVIEW)
I would add it directly in the form layout (so you can see it at design time), and then customize it, bind each column to a database field. The appearance of the grid will be more predictable. Here is a small guide: How to bind datatable/list to datagridview with headers?
Relying on AutoGenerateColumns is not a great idea, because this will show all columns (usually not desirable) and not necessarily in the order that you want.
Other remarks:
Records can be edited or deleted directly in the datagridview, by simply selecting one or more rows, and pressing the Del key. Then just invoke the DataAdapter to commit the changes to the database. You should not even be doing DELETE FROM. Just let the user use the datagridview. The benefit is that if the user makes a mistake, you can roll back changes because you are using a datatable. Here you are deleting immediately and without warning.
Don't do stuff like:
SQL_CMD_TXT = "DELETE FROM `employees` WHERE (`EMPLOYEE_ID` ='" &
EMPLOYEE_DEL_FRM.DEL_ID_TXT.Text & "'); SELECT * FROM `employees`;"
Use parameterized queries instead, this code is insecure and will choke on single quotes or special characters (try it !). Here is a simple example: FAQ: How do I make a parameterized query in the database with VB.NET?. Please use parameterized queries from now on, don't develop bad habits that will always bite you sooner or later. The security risk alone is too high.
Also I am wondering why you did stacked queries. It would better to separate the SELECT from the DELETE.
In this code variable sql is not needed:
With cmd
sql = SQL_CMD_TXT
.Connection = con
.CommandText = sql
End With
Just use SQL_CMD_TXT directly. Otherwise it makes the code more difficult to follow.

'No value given for one or more required parameters.' Error, Can't get over it

I'm trying to take a Yes/No value from my database on Access and make it so if the Yes/No is checked on Access it will check it on the form. Although I keep getting
System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
On the line Dim rs As OleDbDataReader = SQLCmd.ExecuteReader()
Sorry if it's a really easy and stupid mistake, I'm a college student and googling isn't helping me figure this one out.
cn.Open()
Dim SQLCmd As New OleDbCommand
SQLCmd.Connection = cn
SQLCmd.CommandText = "SELECT *, staffIn FROM Staff WHERE staffName = DarrenSloan"
Dim rs As OleDbDataReader = SQLCmd.ExecuteReader()
While rs.Read
Dim DisplayValue As String = rs("staffIn")
SQLCmd.Parameters.AddWithValue("#inorout", inOrOut.Checked)
SQLCmd.ExecuteNonQuery()
End While
cn.Close()
I know this is an old post but I seem to remember that OleDb does not support named parameters.
Also, pretty sure that DarrenSloan should be surrounded by single quotes, like any string value. And indeed, reusing the SQL command like this is not the way to do it.
The CommandText:
SQLCmd.CommandText = "SELECT *, staffIn FROM Staff WHERE staffName = DarrenSloan"
does not contain any parameter.
Thus, the parameter inorout has no effect:
SQLCmd.Parameters.AddWithValue("#inorout", inOrOut.Checked)
Either use two statements, one SELECT and one UPDATE.
Or use a different mechanism like a databound grid. Maybe you are using a datagridview control to display the data. Then there are different techniques to keep the data in sync. It depends on how you choose to render the data on your form.
Firstly, get rid of the loop. You would only use a loop if you were expecting more than one record. By the looks of it, you are expecting only one record, so no loop.
Secondly, stop calling ExecuteNonQuery. That is for making changes to the database, which you're obviously not trying to do. You obviously know how to get data from the query because you're doing it here:
Dim DisplayValue As String = rs("staffIn")
If you want to get data from another field, do the same thing. You can then use that data in whatever way you like, e.g.
Using connection As New OleDbConnection("connection string here"),
command As New OleDbCommand("SELECT * FROM Staff WHERE staffName = 'DarrenSloan'", connection)
connection.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
Dim inOrOut = reader.GetBoolean(reader.GetOrdinal("inorout"))
inOrOutCheckBox.Checked = inOrOut
End If
End Using
End Using
Notice that I have wrapped the text literal in the SQL in single-quotes? I would expect that you would normally not want to hard-code a name there, but use input from the user instead, In that case, you would use a parameter, e.g.
Using connection As New OleDbConnection("connection string here"),
command As New OleDbCommand("SELECT * FROM Staff WHERE staffName = #staffName", connection)
command.Parameters.Add("#staffName", OleDbType.VarChar, 50).Value = staffNameTextBox.Text
connection.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
Dim inOrOut = reader.GetBoolean(reader.GetOrdinal("inorout"))
inOrOutCheckBox.Checked = inOrOut
End If
End Using
End Using

Deleting record by ID

I'm trying to delete a record in my database via the ID, but it says
"Data Type mismatch in criteria expression."
Why do you think so?
Private Sub testdelete()
'THIS SAVES TO THE DEBUG ACCESS DATABASE!!!!!
Dim conn As New OleDbConnection
conn = New OleDbConnection
dbprovider = "Provider=Microsoft.ACE.OLEDB.12.0;"
Dim databasePath = "Data Source = FULL YUGIOH ACCESS DATABASE.accdb;"
conn.ConnectionString = dbprovider & databasePath
Dim Stringc As String = "delete from cmon11 where ID='" & TextBox2.Text & "'"
Dim command As OleDbCommand = New OleDbCommand(Stringc, conn)
Try
conn.Open()
command.ExecuteNonQuery()
command.Dispose()
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
As noted in the comments, a data type mismatch occurs because the where clause in your SQL statement is attempting to compare the value of your field ID (which you have stated is an integer) with a string value.
Following the concatenation, the SQL code might look something like this:
delete from cmon11 where ID='123'
Here, '123' is a string, not an integer - to supply an integer value, you would remove the single quotes to yield:
delete from cmon11 where ID=123
However, this does not solve the underlying issue of the potential for SQL injection when constructing SQL statements using values held by textboxes permitting arbitrary text input.
After modifying your code to remove the single quotes, consider the implications of your user typing the following into the textbox:
;drop table cmon11;--
The solution is to use parameters such that the query will fail in such circumstances, rather than performing unwanted actions. This answer from Erik is an excellent reference detailing the various ways to parameterise queries in MS Access.
The Using...End Using ensure that your database objects are closed and disposed even if there is an error.
Always use parameters to minimize type mismatches and protect against Sql Injection. I guessed at Integer for the datatype of the Id field but you will have to check your database for the actual datatype.
Private Sub testdelete()
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = FULL YUGIOH ACCESS DATABASE.accdb;")
Using command As New OleDbCommand("Delete From cmon11 Where ID= #ID;", conn)
command.Parameters.Add("#ID", OleDbType.Integer).Value = CInt(TextBox2.Text)
conn.Open()
command.ExecuteNonQuery()
End Using
End Using
End Sub

What have I missed out with regards to the syntax of the SQL statement?

I am writing code to insert a username and password into a database called Users.
When I try to run the code it says there is an error in the INSERT statement's syntax but I cannot for the life of me find it.
I am running the SQL statement using another function called RunSQL that I can submit if need be but its worked fine with every other SQL statement I have run with it.
The Users table has the following columns with their data type
User_ID - Auto Number (Primary Key)
Username - Short Text
Password - Short Text
I have tried adding ' ' around the values I am going to insert into the table as well as removing the & and making it one continuous string. I have tried adding / removing the ; but nothing has worked.
Dim sql As String = "INSERT INTO Users (Username, Password) " &
"VALUES (" & username_Textbox.Text & " , " & password_Textbox.Text & ");"
RunSQL(sql)
MessageBox.Show("User Added")
Private Sub RunSQL(ByVal sql As String)
Dim conn As OleDbConnection = New
OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Paper_Gen_Database.accdb;")
conn.Open()
Dim cmd As New OleDbCommand(sql, conn)
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep(500)
End Sub
The code should take the values from the username and password textboxes and insert them into the Users table but so far it has only thrown back an SQL error.
This is what the SQL statement looks when with "bh106" being the Username and "ZLTga" being the Password
This is one way to use parameters. It is very important to use parameters because otherwise you risk SQL injection which can ruin your database. It is actually much easier to write the SQL statement this way because you don't have to worry about if you have all your quotes in the string correctly.
The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error. This is important because it releases any unmanaged resources being used.
In a real application you would never save passwords as plain text but that is a subject for another day.
Private Sub InsertUser()
Dim sql As String = "INSERT INTO Users (Username, [Password]) VALUES (#username, #password);"
Using conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Paper_Gen_Database.accdb;")
Using cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = username_Textbox.Text
cmd.Parameters.Add("#password", OleDbType.VarChar).Value = password_Textbox.Text
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("User Added")
End Sub
In Access the order that the parameters are added must match the order that they appear in the SQL statement.
Try this (its probably because of lack of quotes, and also because password is protected word):
Dim sql As String = "INSERT INTO Users (Username, [Password]) " &
"VALUES ('" & username_Textbox.Text & "' , '" & password_Textbox.Text & "');"
RunSQL(sql)
MessageBox.Show("User Added")
Also be aware of sql injection problem.
If a user will put a quote inside a textbox, insert will still fail.
You should try converting your code into parametrized query, example:
https://learn.microsoft.com/pl-pl/dotnet/api/system.data.oledb.oledbcommand.parameters?view=netframework-4.7.2

VB Access DB Update statement

I am new to this forum, please could you help me get this code to work, when i execute it, it simply does nothing and does not update the DB. If i remove the square brackets it gives an error: "SYNTAX ERROR in UPDATE statement"
Any help appreciated!
Dim connection As OleDbConnection
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserDB.accdb;Jet OLEDB:Database;")
connection.Open()
Dim pass As String
pass = txtconfirm.Text
Dim user As String
user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= '" & pass & "' WHERE [Username]= '" & user & "';"
Dim command As New OleDbCommand(query, connection)
command.ExecuteNonQuery()
connection.Close()
Given your actual connection string, the database that will be updated is the one in the directory where your application starts. This means that if you work with a WinForms application this folder is \BIN\DEBUG or x86 variant. If there is not error then you could get the return value of the ExecuteNonQuery call to verify if a record has been updated or not
Dim rowsUpdated = command.ExecuteNonQuery()
MessageBox.Show("Record updated count = " & rowsUpdated)
If this value is not zero then your database has been updated and you are looking for changes in the wrong database. Check the one in the BIN\DEBUG folder.
In any case your code has big problems. If your variables user or pass contain a single quote, then your code will crash again because your string concatenation will form an invalid SQL. As usual the only workaround is to use a parameterized query
Dim pass = txtconfirm.Text
Dim user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= #p1 WHERE [Username]= #p2"
Using connection = New OleDbConnection("...........")
Using command As New OleDbCommand(query, connection)
connection.Open()
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = pass
command.Parameters.Add("#p2", OleDbType.VarWChar).Value = user
command.ExecuteNonQuery()
End Using
End Using
The parameterized approach has many advantages. Your query text is more readable, there is no misunderstanding between your code and the values expected by your database engine. And while not easy to exploit with MS-Access there is no problem with Sql Injection
I think Steve presents a much better approach for you coding this...
Let me just throw out a few more things:
The reason you can't take those brackets out is some of your column names are reserved words; just FYI.
Since you report "it does nothing..." when you execute, it sounds like you have a valid connection and sql syntax, in which case my next step would be to copy the sql command text while in debug mode, change it to a select and run it in your DB. You should get one result when you do. If not, either your criteria or field contents are not what you think they are...
Just change the Update table SET field-value ... to SELECT * FROM table and leave the WHERE clause as is.