Inserting and Updating values in MS Access Using vb.net - vb.net

I have checked most of the forums on this site but I didn't get my Solution.
My problem is Inserting data from vb.net to MS Access but I am not able to do.
Its not showing any error but also its not inserting values in my table.
I am using very simple code:
Imports System.Data.OleDb
Public Class Add_LEads
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Private Sub Add_LEads_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\IndGlobalDB.accdb;Persist Security Info=True;Jet OLEDB:Database Password=admin")
lblDate.Text = Format(Date.Now, "yyyy/MM/dd")
conn.Open()
Dim sql As String
Dim a As Integer
sql = "select S_No from Leadss"
cmd = New OleDbCommand(sql, conn)
Dim dr As OleDbDataReader
dr = cmd.ExecuteReader
While dr.Read
a = dr(0)
End While
lblNo.Text = a + 1
conn.Close()
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO Leadss(S_No,Contact_Person,Mobile_No,Email_Id,Description,First_Follow_Up,Remarks,L_Date,Alternate_no)VALUES('" & lblNo.Text & "','" & txtName.Text & "','" & txtMobile.Text & "','" & txtEmail.Text & "','" & txtWebDescr.Text & "','" & txtFollowUp.Text & "','" & txtRemarks.Text & "','" & lblDate.Text & "','" & txtAlternate.Text & "')"
cmd.ExecuteNonQuery()
conn.Close()
MsgBox("Saved!!!", vbOK)
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
Welcome.Show()
End Sub
End Class

You should use parametrized query to avoid Sql Injection Attacks and let the JET engine parse your string parameters for invalid characters.
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnSave.Click
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO Leadss(S_No,Contact_Person,Mobile_No,Email_Id," & _
"Description,First_Follow_Up,Remarks,L_Date,Alternate_no) VALUES " & _
"(?, ?, ?, ?, ?, ?, ?, ?, ?)"
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#p1", lblNo.Text)
cmd.Parameters.AddWithValue("#p2", txtName.Text)
cmd.Parameters.AddWithValue("#p3", txtMobile.Text)
cmd.Parameters.AddWithValue("#p4", txtEmail.Text)
cmd.Parameters.AddWithValue("#p5", txtWebDescr.Text)
cmd.Parameters.AddWithValue("#p6", txtFollowUp.Text)
cmd.Parameters.AddWithValue("#p7", txtRemarks.Text)
cmd.Parameters.AddWithValue("#p8", lblDate.Text)
cmd.Parameters.AddWithValue("#p9", txtAlternate.Text)
cmd.ExecuteNonQuery()
conn.Close()
End Sub
Said that, this works only if your field types are of text type and not numeric or datetime or boolean, in that case your should convert the input text in the appropriate type using Convert.ToXXXXX methods.
(The example below assumes that your inputs contains valid numbers and dates)
....
cmd.Parameters.AddWithValue("#p3", Convert.ToInt32(txtMobile.Text))
.....
cmd.Parameters.AddWithValue("#p8", Convert.ToDateTime(lblDate.Text))
cmd.Parameters.AddWithValue("#p9", Convert.ToInt32(txtAlternate.Text))
Another wrong approach is to keep global variables for reuse like your OleDbConnection, OleDbCommand.
This prevent the runtime to dispose these objects when not used. Instead you should follow this approach
Using conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data " +
"Source=|DataDirectory|\IndGlobalDB.accdb;" +
"Persist Security Info=True;Jet OLEDB:Database Password=admin")
Using cmd = New OleDbCommand()
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO ................"
cmd.Parameters.AddWithValue("#p1", lblNo.Text)
..........
End Using
End Using

Here's a simple example for the use of SqlParameter and the try/catch block:
Dim connection As SqlConnection = As New SqlConnection("YourDbConnection")
Dim command As SqlCommand = connection.CreateCommand()
Try
connection.Open()
command.CommandText = "INSERT INTO Leadss(S_No) VALUES (#S_No)"
command.Parameters.Add("#S_No", SqlDbType.Text)
command.Parameters["#FirstName"].Value = lblNo.Text
command.ExecuteNonQuery()
Catch Ex As SqlException
'Process the exception
Finally
connection.Close()
End Try

Use Backticks (`) in your FROM Statement. It should be FROM(`Field1`,`Field2`,...etc) Values('value1', 'value2').

write this coding according to your database name, table name, field names in save button's click event...
Using conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\user\Documents\Visual Studio 2008\Projects\demo for db in access\demo for db in access\DatabaseforDemo.accdb'")
Using cmd = New OleDbCommand()
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO demo1(Name) VALUES('" & TextBox1.Text & "')"
'cmd.Parameters.AddWithValue("#p1", lblNo.Text)
cmd.ExecuteNonQuery()
MsgBox("saved..")
conn.Close()
End Using
End Using
good luck...
hope so it'll help you...!

In your question you said:
Its not showing any error but also its not inserting values in my table
Try to use Commit.
A COMMIT statement in SQL ends a transaction within a relational database management system (RDBMS) and makes all changes visible to other users. The general format is to issue a BEGIN WORK statement, one or more SQL statements, and then the COMMIT statement. Alternatively, a ROLLBACK statement can be issued, which undoes all the work performed since BEGIN WORK was issued. A COMMIT statement will also release any existing savepoints that may be in use.
In terms of transactions, the opposite of commit is to discard the tentative changes of a transaction, a rollback.
quoted here: Commit (data management)
Try
'Open Connection...
'Insert Statement....
'Notification / Msgbox to confirm successful transaction
Catch ex As Exception
'RollBack Transaction...
'Error Management...
Finally
'Commit...
'Close DB Connection....
End Try
Microsoft Documentation: OleDbTransaction.Commit Method ()
but remember: you should use transactions only if you are inserting/updating multiple SQL statements which then make sense for the rollback.
Here is an Example in Adding transaction management into a form using MS Access 2010

Related

How to restrict user to not update the date and the week textbox

My question is "The user should be able to update (edit) a previously entered log but the date and the week number should be prevented from being edited"
How do I restrict user to not update the date and the week textbox?
Here is my current update code:
Private Sub Btnupdatelog_Click(sender As Object, e As EventArgs) Handles Btnupdatelog.Click
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
cmd = New SqlCommand("update Logbook Objectives='" & Txtobjectives.Text & "',Contents='" & Txtcontent.Text & "',Company_Signature_Stamp='" & Txtsignature.Text & "',Company_Date='" & DateTimePicker2.Text & "' where LogId=" & TxtLogId.Text & "", conn)
conn.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Alex\source\repos\CurriculumVitae(CV)\bin\Debug\CurriculumVitae(CV).mdf;Integrated Security=True;Connect Timeout=30"
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
MsgBox("Update Successfully")
End Sub
End Class
To prevent certain fields from being update, simply don't include those fields in the command text. I removed the date field from the text.
Database objects need to be closed and disposed. Using...End Using blocks handle this for you even if there is an error. In this code, both the connection and command are included in the Using block. Note the comma at the end of the first line of the Using.
Never concatenate strings to build sql text. Always use parameters to avoid sql injection. I had to guess at the datatype and size of your fields. Check your database for the correct values.
Private Sub Btnupdatelog_Click(sender As Object, e As EventArgs) Handles Btnupdatelog.Click
Using conn As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Alex\source\repos\CurriculumVitae(CV)\bin\Debug\CurriculumVitae(CV).mdf;Integrated Security=True;Connect Timeout=30"),
cmd As New SqlCommand("update Logbook Set Objectives= #Objectives, Contents= #Contents, Company_Signature_Stamp= #Signature where LogId= #ID;", conn)
With cmd.Parameters
.Add("#Objectives", SqlDbType.VarChar, 300).Value = Txtobjectives.Text
.Add("#Contents", SqlDbType.VarChar, 300).Value = Txtcontent.Text
.Add("#Signature", SqlDbType.VarChar, 100).Value = Txtsignature.Text
.Add("#ID", SqlDbType.Int).Value = CInt(TxtLogId.Text)
End With
conn.Open()
cmd.ExecuteNonQuery()
End Using
MsgBox("Update Successfully")
End Sub

What's wrong with this SQL Insert statement of mine?

I am trying to add a record to my table, however I'm getting an exception after it attempts to do so. I am able to open the connection successfully, (my first messagebox shows up) but after that I get the exception. Here's my code:
Private Sub btnUpdateInfo_Click(sender As Object, e As EventArgs) Handles btnUpdateInfo.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con = New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=CISDB;Integrated Security=SSPI;")
Try
cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (txtFirstName.Text, txtLastName.Text)"
cmd.Connection = con
con.Open()
MsgBox("Connection Open ! ")
cmd.ExecuteNonQuery()
MsgBox("Record inserted")
con.Close()
Catch ex As Exception
MsgBox("Error!")
End Try
End Sub
For future readers - Sql parameters will save a lot of your and your coworkers time.
Private Sub btnUpdateInfo_Click(sender As Object, e As EventArgs) Handles btnUpdateInfo.Click
Dim connString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=CISDB;Integrated Security=SSPI;"
Using connection As New SqlConnection(connString)
Using command As New SqlCommand(connection)
command.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (#FirstName, #Lastname)"
Dim params As SqlParameter() =
{
New SqlParameter With { .ParameterName = "#FirstName", .SqlDbType.VarChar, .Value = txtFirstName.Text },
New SqlParameter With { .ParameterName = "#LastName", .SqlDbType.VarChar, .Value = txtLastName.Text },
}
command.Parameters.AddRange(params)
connection.Open()
command.ExecuteNonQuery()
' Inserted
End Using
End Using
End Sub
Same for try.. catch(as #Plutonix has noticed in the comments) - if you will get "real" exception you will find reason and solution much faster
You need to look at the exception message (ex.Message) see what the issue is...If you have an error similar to multipart identifier then try this query string instead of your current query string for a quick test.
cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES ('" & txtFirstName.Text & "', '" & txtLastName.Text & "')"
Check out parameterized query as previously indicated

ExecuteReader: CommandText property has not been initialized when trying to make a register form for my database

hello guys im trying to script a register form for my database and i came with this code >> so can anyone help ?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cmd.CommandText = "INSERT INTO test2(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("You're already registered")
Else
MsgBox("Already registered")
End If
End Sub
Edit your Code in this way..
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Insert will not retrieve any records it's a SELECT statement you want to use .I'll suggest you use stored procedures instead to avoid Sql-Injections.
ExecuteReader it's for "SELECT" queries, that helps to fill a DataTable. In this case you execute command before cmd.commandText is defined.
You should have define cmd.commandText before and use ExecuteNonQuery after, like this.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cn.Open()
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd.ExecuteNonQuery()
cn.Close()
cmd.CommandText should be assigned stored proc name or actual raw SQL statement before calling cmd.ExecuteReader
Update:
Change code as follows
....
cmd.Connection = cn
cmd.CommandText = "select * from TblToRead where <filter>" ''This is select query statement missing from your code
cn.Open()
dr = cmd.ExecuteReader ....
where <filter> will be something like username = "' & Request.form("username') & '" '
The error itself is happening because you're trying to execute a query before you define that query:
dr = cmd.ExecuteReader
'...
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Naturally, that doesn't make sense. You have to tell the computer what code to execute before it can execute that code:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
'...
dr = cmd.ExecuteReader
However, that's not your only issue...
You're also trying to execute a DataReader, but your SQL command doesn't return data. It's an INSERT command, not a SELECT command. So you just need to execute it directly:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
cmd.ExecuteNonQuery
One value you can read from an INSERT command is the number of rows affected. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Dim affectedRows as Int32 = cmd.ExecuteNonQuery
At this point affectedRows will contain the number of rows which the query inserted successfully. So if it's 0 then something went wrong:
If affectedRows < 1 Then
'No rows were inserted, alert the user maybe?
End If
Additionally, and this is important, your code is wide open to SQL injection. Don't directly execute user input as code in your database. Instead, pass it as a parameter value to a pre-defined query. Basically, treat user input as values instead of as executable code. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES(#Username,#Password)"
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = TextBox2.Text
(Note: I guessed on the column types and column sizes. Adjust as necessary for your table definition.)
Also, please don't store user passwords as plain text. That's grossly irresponsible to your users and risks exposing their private data (even private data on other sites you don't control, if they re-use passwords). User passwords should be obscured with a 1-way hash and should never be retrievable, not even by you as the system owner.
You're attempting to change the CommandText after you're executing your query.
Try this:
Private cn = New SqlConnection("Server=localhost;Database=test;UID=sa;PWD=secret")
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.CommandText = "select * from table1" ' your sql query selecting data goes here
Dim dr As SqlDataReader
cmd.Connection = cn
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows = 0 Then
InsertNewData(TextBox1.Text, TextBox2.Text)
Else
MsgBox("Already registered")
End If
End Sub
Private Sub InsertNewData(ByVal username As String, ByVal password As String)
Dim sql = "INSERT INTO User_Data(Username,Password) VALUES(#Username, #Password)"
Dim args As New List(Of SqlParameter)
args.Add(New SqlParameter("#Username", username))
args.Add(New SqlParameter("#Password", password))
Dim cmd As New SqlCommand(sql, cn)
cmd.Parameters.AddRange(args.ToArray())
If Not cn.ConnectionState.Open Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cn.Close()
End Sub
This code refers the INSERT command to another procedure where you can create a new SqlCommand to do it.
I've also updated your SQL query here to use SqlParameters which is much more secure than adding the values into the string directly. See SQL Injection.
The InsertNewData method builds the SQL Command with an array of SQLParameters, ensures that the connection is open and executes the insert command.
Hope this helps!

transaction in ms access and vb.net

I am trying the below code but not getting executed.
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Using con As New OleDbConnection(connectionString)
Dim tra As OleDbTransaction = Nothing
Try
con.Open()
cmd.Transaction = tra
tra = con.BeginTransaction
Dim sqlstr As String = "insert into category(cname,comment) values('" + txtcategory.Text + "','" + txtcomment.Text + "')"
cmd = New OleDb.OleDbCommand(sqlstr, con)
cmd.ExecuteNonQuery()
Dim sql As String = "UPDATE tblInvoices SET avail = 1 WHERE (cname = txtcategory.Text)"
cmd = New OleDb.OleDbCommand(sqlstr, con)
cmd.ExecuteNonQuery()
tra.Commit()
Catch ex As Exception
MsgBox(ex.Message)
Try : tra.Rollback() : Catch : End Try
End Try
End Using
End Sub
I don't understand the transactions.
The command need to know about the existence of a Transaction. But you assign the Transaction instance before the opening the connection and then ask the connection to start the transaction.
In this way the command has a null reference for the transaction and not the good instance created by the connection. Also, when you create again the command, there is no transaction associated with it.
Better use the OleDbCommand constructor that takes a Transaction as third parameter
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Using con As New OleDbConnection(connectionString)
Dim tra As OleDbTransaction = Nothing
Try
con.Open()
tra = con.BeginTransaction
Dim sqlstr As String = "insert into category(cname,comment)" &
" values(#cat, #com)"
cmd = New OleDb.OleDbCommand(sqlstr, con, tra)
cmd.Parameters.Add("#cat", OleDbType.VarWChar).Value = txtcategory.Text
cmd.Parameters.Add("#com", OleDbType.VarWChar).Value = txtcomment.Text
cmd.ExecuteNonQuery()
Dim sql As String = "UPDATE tblInvoices SET avail = 1 " &
"WHERE cname = #cat"
cmd = New OleDb.OleDbCommand(sqlstr, con, tra)
cmd.Parameters.Add("#car", OleDbType.VarWChar).Value = txtcategory.Text
cmd.ExecuteNonQuery()
tra.Commit()
Catch ex As Exception
MsgBox(ex.Message)
tra.Rollback()
End Try
End Using
End
I have also changed your code to use a more safe approach to your queries. Instead of using a string concatenation use ALWAYS a parameterized query. In this way you are safe from Sql Injection, you don't have problems with parsing texts and your queries are more readable.

Error in vb.net code in INSERT INTO

When I try to insert data in these three field gets an error saying error in INSERT INTO Statement.
but when a save in only the first field sname it gets added but when adds other two gets this error
I am getting an exception in INSERT INTO Statement check below
any advice?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Taher\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\Database1.accdb;Persist Security Info=False;"
Me.con = New OleDb.OleDbConnection()
con.ConnectionString = dbprovider
con.Open()
Dim sqlquery As String = "INSERT INTO admin (sname,username,password)" + "VALUES ('" & txtname.Text & "','" & txtuser.Text & "','" & txtpass.Text & "');"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.ExecuteNonQuery()
con.Close()
End With
MsgBox("User Registered")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The word PASSWORD is a reserved keyword in JET-SQL for Microsoft Access. If you have a column with that name you should encapsulate it with square brackets
"INSERT INTO admin (sname,username,[password])" &% _
"VALUES ('" & txtname.Text & "','" & txtuser.Text & _
"','" & txtpass.Text & "');"
That's the reason of the syntax error, however let me tell you that building sql commands concatenating strings is a very bad practice. You will have problems when your values contain single quotes and worst of all, your code could be used for sql injection Attacks
So your code should be changed in this way
Dim sqlquery As String = "INSERT INTO admin (sname,username,password)" & _
"VALUES (?, ?, ?)"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.Parameters.AddWithValue("#p1", txtname.Text)
.Parameters.AddWithValue("#p2", txtuser.Text)
.Parameters.AddWithValue("#p3", txtpass.Text)
.ExecuteNonQuery()
con.Close()
End With
also your use of the object OleDbConnection doesn't follow a good pattern. In case of exception you don't close the connection and this could be a problem in reusing the connection in subsequent calls.
You should try to use the Using statement
Using connection = New OleDb.OleDbConnection()
connection.ConnectionString = dbprovider
connection.Open()
.....
' rest of command code here '
' No need to close the connection
End Using
in this way, also if you get an exception the OleDbConnection will be closed and disposed without impact on system resource usage.