System.Data.SqlClient.SqlException: Violation of PRIMARY KEY - sql

I create a SQL Server database and I want to add some data in a particular table of that database. I use some textbox to input the data and an add button to complete. But when I tap the button the whole process was stopped and indicate an error in the DBSQL module which is shown below.
Here's my code:
Imports System.Data
Imports System.Data.SqlClient
Module DBSQLServer
Public con As New SqlConnection("Data Source=JOYALXDESKTOP\SQLEXPRESS;Initial Catalog=SaleInventory;Integrated Security=True")
Public cmd As New SqlCommand
Public da As New SqlDataAdapter
Public ds As New DataSet
Public dt As DataTable
Public qr As String
Public i As Integer
Public Function searchdata(ByVal qr As String) As DataSet
da = New SqlDataAdapter(qr, con)
ds = New DataSet
da.Fill(ds)
Return ds
End Function
Public Function insertdata(ByVal qr As String) As Integer
cmd = New SqlCommand(qr, con)
con.Open()
i = cmd.ExecuteNonQuery()
con.Close()
Return i
End Function
End Module
The error occurs on this line:
i = cmd.ExecuteNonQuery()
In the table, I have 5 columns:
ProID, ProName, ProDesc, ProPrice, ProStock
ProID is my primary key.
Here's my add button code to add the data into the database:
Private Sub Add_Click(sender As Object, e As EventArgs) Handles add.Click
If (isformvalid()) Then
qr = "Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "')"
Dim logincorrect As Boolean = Convert.ToBoolean(insertdata(qr))
If (logincorrect) Then
MsgBox("Stock Added Successfully ...", MsgBoxStyle.Information)
Else
MsgBox("Something Wrong. Record Not Saved. Please Check and Try Again...", MsgBoxStyle.Critical)
End If
End If
End Sub
When my query is:
qr = "Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "')"
The error is below :
System.Data.SqlClient.SqlException: 'Cannot insert the value NULL into column 'ProID', table 'SaleInventory.dbo.tblProductInfo'; column does not allow nulls. INSERT fails.
And when my query is:
qr = "Insert into tblProductInfo (ProID, ProName, ProDesc, ProPrice, ProStock) Values('" & idtext.Text & "','" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "')" `
Then the error is:
System.Data.SqlClient.SqlException: 'Violation of PRIMARY KEY constraint 'PK_tblProductInfo'. Cannot insert duplicate key in object 'dbo.tblProductInfo'. The duplicate key value is (1).

This is because in tblProductInfo there is a row with ProID=1. You should code so that avoid this duplicate, for example you can first run a script to find the maximum of ProID in your table ("Select MAX(ProID) from tblProductInfo"), and run your query with MAX(ProID)+1.

Assuming you have corrected your database making the ProdID an identity field.
Notice that all interaction with the user interface is performed in the Form code. All interaction with the database is performed in the Module. Although you still need to Import System.Data (for the DataTable type) it is not necessay to Import System.Data.SqlClient in the Form. All validation is done in the Form.
In the Module code, the Using...EndUsing blocks ensure that your database objects are closed and disposed even if there is an error. I have demonstrated how to use parameters to avoid Sql injection but I had to guess at the datatypes. Check your database for the actual datatypes and adjust the SqlDbType and the parameter types and the validation code in the Form accordingly.
Connections are precious resources. Notice that the connection is opened at the last minute and closed and disposed by the End Using immediately after it is used by and .Execute...
Module DBSQLServer
Private conString As String = "Data Source=JOYALXDESKTOP\SQLEXPRESS;Initial Catalog=SaleInventory;Integrated Security=True"
'Example of how your search function might look.
Public Function searchdata(Name As String) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection()
Using cmd As New SqlCommand("Select * From tblProductInfo Where Name = #Name", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = Name
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
Public Function insertdata(Name As String, Description As String, Price As Decimal, Stock As Integer) As Integer
Dim i As Integer
Using cn As New SqlConnection(conString)
Using cmd As New SqlCommand("Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values(#Name,#Description, #Price, #Stock", cn)
With cmd.Parameters
.Add("#Name", SqlDbType.VarChar).Value = Name
.Add("#Description", SqlDbType.VarChar).Value = Description
.Add("#Price", SqlDbType.Decimal).Value = Price
.Add("#Stock", SqlDbType.Int).Value = Stock
End With
cn.Open()
i = cmd.ExecuteNonQuery
End Using
End Using
Return i
End Function
End Module
And in the form
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'First check that text boxes for string parameters are filled in
If nametext.Text = "" OrElse descriptiontext.Text = "" Then
MessageBox.Show("Please fill in all text boxes.")
Return
End If
'Next check for valid numeric values
Dim price As Decimal
If Not Decimal.TryParse(pricetext.Text, price) Then
MessageBox.Show("The price must be a number.")
Return
End If
Dim stock As Integer
If Not Integer.TryParse(stocktext.Text, stock) Then
MessageBox.Show("Stock must be a whole number")
Return
End If
Dim retVal As Integer = DBSQLServer.insertdata(nametext.Text, descriptiontext.Text, price, stock)
If retVal = 1 Then
MessageBox.Show("Product successfully added.")
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dt = DBSQLServer.searchdata(txtSearch.Text)
DataGridView1.DataSource = dt
End Sub

Related

My code is not working due to an error when inserting data into the database

Imports System.Data.SqlClient
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim A As New SqlConnection
Dim cmdd As New SqlCommand
Dim R As SqlDataReader
A.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\SurAj\AppData\Local\Temporary Projects\RPS\connectivity.mdf;Integrated Security=True"
A.Open()
cmdd.Connection = A
cmdd.CommandType = CommandType.Text
cmdd.CommandText = "select * from T where emailid='" & emailid.Text & "' "
R = cmdd.ExecuteReader
If R.HasRows Then
MsgBox("ADD Another Email Id", MsgBoxStyle.Critical, "Error: Try Again")
A.Close()
Else
A.Close()
A.Open()
cmdd = New SqlCommand("INSERT INTO T values('" & fullnames.Text & "','" & emailid.Text & "','" & loginU.Text & "','" & loginP.Text & "')", A)
If (fullnames.Text = String.Empty Or emailid.Text = String.Empty Or loginU.Text = String.Empty Or loginP.Text = String.Empty) Then
MessageBox.Show("You missed some details", "ERROR")
Else
cmdd.ExecuteNonQuery()
MsgBox("Successfully registered.", MsgBoxStyle.Information, "Success")
Me.Hide()
Form3.Show()
fullnames.Clear()
emailid.Clear()
loginU.Clear()
loginP.Clear()
End If
A.Close()
End If
A.Close()
' Catch ex As Exception
'MsgBox("Error")
'End Try
End Sub
End Class
I get an error at cmdd.ExecuteNonQuery:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Column name or number of supplied values does not match table definition.
even though all columns are mentioned. What's wrong? I'm not getting it.
Your table is defined as:
CREATE TABLE [dbo].[T]
(
[Id] INT NOT NULL,
[fullnames] VARCHAR(50) NOT NULL,
[emailid] VARCHAR(50) NOT NULL,
[loginU] VARCHAR(50) NOT NULL,
[loginP] VARCHAR(50) NOT NULL
);
and your insert statement only inserts value for fullnames, emailid, loginU and loginP - but NOT for Id:
cmdd = New SqlCommand("INSERT INTO T VALUES('" & fullnames.Text & "','" & emailid.Text & "','" & loginU.Text & "','" & loginP.Text & "')", A)
--> you're NOT proving values for all columns in your table.
Furthermore, as I mentioned in comments - you should NEVER EVER concatenate together your SQL statements like this - use parameters - ALWAYS!
Also, it is a generally accepted best practice to list your columns of the table you're inserting into.
So all in all, your insert statement should be something like:
string insertQry = #"INSERT INTO T (id, fullnames, emailid, loginU, loginP)
VALUES (#id, #fullnames, #emailid, #loginU, #loginP);";
cmdd.CommandText = insertQry;
// add the parameters and their values here
I have divided the code into user interface and data access. The user interface knows nothing about where the data is being sent. It could be Oracle, MS Access or even a text file. It doesn't matter to the user interface.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Do your validation first
If fullnames.Text = String.Empty OrElse emailid.Text = String.Empty OrElse loginU.Text = String.Empty OrElse loginP.Text = String.Empty Then
MessageBox.Show("You missed some details", "ERROR")
Exit Sub
End If
Dim id As Integer 'I don't know where this value is coming from
Try
Dim inserts = InsertUser(id, fullnames.Text, emailid.text, loginU.Text, loginP.Text)
If inserts = 1 Then
MsgBox("Successfully registered.", MsgBoxStyle.Information, "Success")
Me.Hide()
Form3.Show()
fullnames.Clear()
emailid.Clear()
loginU.Clear()
loginP.Clear()
Else
MessageBox.Show("Addition not successful. The email already exists.")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Likewise, the InsertUser function where the data is coming from. It could be a Web app, a WPF application or WinForms.
The command text combines checking if the email already exists in the database and the actually insert.
Using...End Using blocks ensure that your database objects are closed and disposed even it there is an error.
Always use Parameters. http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Here is another
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
Private Function InsertUser(id As Integer, name As String, email As String, user As String, pword As String) As Integer
Dim RecordsEntered As Integer
Dim sql = "If Not Exists(Select * From T Where emailid = #emailid)
Insert Into T (Id, fullnames, emailid, loginU, loginP)
Values (#Id, #fullnames, #emailid, #loginU, #loginP);"
Using A As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\SurAj\AppData\Local\Temporary Projects\RPS\connectivity.mdf;Integrated Security=True"),
cmdd As New SqlCommand(sql, A)
With cmdd.Parameters
.Add("#Id", SqlDbType.Int).Value = id
.Add("#fullnames", SqlDbType.VarChar, 50).Value = name
.Add("#emailid", SqlDbType.VarChar, 50).Value = email
.Add("#loginU", SqlDbType.VarChar, 50).Value = user
.Add("#loginP", SqlDbType.VarChar, 50).Value = pword
End With
A.Open()
RecordsEntered = cmdd.ExecuteNonQuery 'Returns -1 if no records are inserted
End Using
Return RecordsEntered
End Function
Another problem which I did not is address is passwords. They should NEVER be stored as plain text. Have a look at encryption.

How to save integer and decimal datatype from datagridview to database ms access in VB.NET [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I have been searching for a solution for my code error, which says that there is a data mismatch to my database declared datatype. I am saving my data grid view's data into ms access database but it show an error of data mismatch for saving PRICE and QUANTITY data.
I have tried adding parameters and it shows the error System.NullReferenceException: 'Object reference not set to an instance of an object.'
'After comfirm only save in database
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If (MessageBox.Show("Comfrim the orders?", "Comfirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes) Then
If OrderDataGridView.Rows.Count > 0 Then
DBConnect = New OleDbConnection
DBConnect.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source = ViewOrder.mdb"
For i As Integer = OrderDataGridView.Rows.Count - 1 To 0 Step -1
Dim Query As String
Query = "INSERT INTO ViewOrder.Order (Serve,Table_No, Item_Code, Item_Name, Quantity, Price, Remarks)
VALUES (#Serve, #Table_No, #Item_Code, Item_Name, #Quantity, #Price, #Remarks)"
Dim cmd As New OleDb.OleDbCommand(Query, DBConnect)
cmd.Parameters.Add("#Serve", OleDbType.VarChar).Value = Label8.Text
cmd.Parameters.Add("#Table_No", OleDbType.VarChar).Value = Label10.Text
cmd.Parameters.Add("#Item_Code", OleDbType.VarChar).Value = OrderDataGridView.Rows(i).Cells(0).Value
cmd.Parameters.Add("#Item_Name", OleDbType.VarChar).Value = OrderDataGridView.Rows(i).Cells(1).Value
cmd.Parameters.Add("#Quantity", OleDbType.Integer).Value = OrderDataGridView.Rows(i).Cells(2).Value
cmd.Parameters.Add("#Price", OleDbType.Decimal).Value = OrderDataGridView.Rows(i).Cells(3).Value
cmd.Parameters.Add("#Remarks", OleDbType.VarChar).Value = OrderDataGridView.Rows(i).Cells(4).Value
DBConnect.Open()
Dim Reader As OleDbDataReader
Reader = command.ExecuteReader
DBConnect.Close()
Next
End If
End If
End Sub
But it still show the error.
This is my current code with the error of data mismatch.
Dim Query As String
Query = "INSERT INTO ViewOrder.Order (Serve,Table_No, Item_Code, Item_Name, Quantity, Price, Remarks) VALUES ('" & Label8.Text & "','" & Label10.Text & "','" & OrderDataGridView.Rows(i).Cells(0).Value & "', '" & OrderDataGridView.Rows(i).Cells(1).Value & "','" & OrderDataGridView.Rows(i).Cells(2).Value & "','" & OrderDataGridView.Rows(i).Cells(3).Value & "','" & OrderDataGridView.Rows(i).Cells(4).Value & "')"
Dim Reader As OleDbDataReader
command = New OleDbCommand(Query, DBConnect)
Reader = command.ExecuteReader
DBConnect.Close()
I just need to save the data in database.
From the MS Docs
the order in which OleDbParameter objects are added to the
OleDbParameterCollection must directly correspond to the position of
the question mark placeholder for the parameter in the command text.
Instead of question marks, I like to use parameter names. It is easier to see if I have the order correct. We add the parameters outside the loop because each iteration uses the same parameters. We don't want to keep adding them. Only the values change but not for Serve and TableNo which stay the same for all the Inserts.
Pass the connection string directly to the constructor of the connection.
The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
You do not want a reader for an Insert. A reader is for returned records. You need .ExecuteNonQuery.
You need to check the datatypes of the fields because I just guessed.
The DataGridView.Rows.Count is -2 because subtract one for counting starting at one and collections starting at zero. And subtract another one for the empty row at the bottom of the grid that is included in the count.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Query As String = "INSERT INTO ViewOrder.Order (Serve,Table_No, Item_Code, Item_Name, Quantity, Price, Remarks)
Values(#Serve, #TableNo, #ItemCode,#ItemName, #Quantity, #Price, #Remarks);"
Using DBConnect = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source = ViewOrder.mdb")
Using cmd As New OleDbCommand(Query, DBConnect)
cmd.Parameters.Add("#Serve", OleDbType.VarChar).Value = Label8.Text
cmd.Parameters.Add("#TableNo", OleDbType.VarChar).Value = Label10.Text
cmd.Parameters.Add("#ItemCode", OleDbType.VarChar)
cmd.Parameters.Add("#ItemName", OleDbType.VarChar)
cmd.Parameters.Add("#Quantity", OleDbType.Integer)
cmd.Parameters.Add("#Price", OleDbType.Decimal)
cmd.Parameters.Add("#Remarks", OleDbType.VarChar)
DBConnect.Open()
For i As Integer = 0 To DataGridView1.Rows.Count - 2
cmd.Parameters("#ItemCode").Value = OrderDataGridView.Rows(i).Cells(0).Value
cmd.Parameters("#ItemName").Value = OrderDataGridView.Rows(i).Cells(1).Value
cmd.Parameters("#Quantity").Value = CInt(OrderDataGridView.Rows(i).Cells(2).Value)
cmd.Parameters("#Price").Value = CDec(OrderDataGridView.Rows(i).Cells(3).Value)
cmd.Parameters("#Remarks").Value = OrderDataGridView.Rows(i).Cells(4).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub

VB.net insert into error [duplicate]

This question already has an answer here:
Syntax error in INSERT INTO Statement when writing to Access
(1 answer)
Closed 7 years ago.
I'm using Microsoft Visual Studio 2013 and im trying to make a registration form for my account database using VB.NET. This is my code so far:
Private Sub btnRegistery_Click(sender As Object, e As EventArgs) Handles btnRegistery.Click
Dim usernme, passwrd As String
usernme = txtUsernm.Text
passwrd = txtpasswrd.Text
Dim myconnection As OleDbConnection
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hasan\Documents\Visual Studio 2012\Projects\hasan\Login_Info.accdb"
myconnection = New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String
sqlQry = "INSERT INTO tbl_user(username, password) VALUES(usernme , passwrd)"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
cmd.ExecuteNonQuery()
End Sub
The code compiles fine, but when i try to register any new information i get the following message:
A first chance exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
If there is a handler for this exception, the program may be safely continued.
What could be a solution and cause for this problem?
Your query seems wrong: ... VALUES(usernme, passwrd)... --
Here the usernmeand passwrd are not variables for database, but just plain text in the query.
Use parameters, like this:
Dim usernme, passwrd As String
usernme = txtUsernm.Text
passwrd = txtpasswrd.Text
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hasan\Documents\Visual Studio 2012\Projects\hasan\Login_Info.accdb"
Using myconnection As New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String = "INSERT INTO [tbl_user] ([username], [password]) VALUES (#usernme, #passwrd)"
Using cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("#usernme", usernme)
cmd.Parameters.AddWithValue("#passwrd", passwrd)
cmd.ExecuteNonQuery()
End using
End using
You aren't including the actual variable information missing the quotations, like
VALUES ('" & usernme & '", ...etc
You should be using parameters to avoid errors and sql injection:
sqlQry = "INSERT INTO tbl_user (username, password) VALUES(#usernme, #passwrd)"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("#usernme", usernme)
cmd.Parameters.AddWithValue("#passwrd", passwrd)
cmd.ExecuteNonQuery()
Dim cnn As New OleDb.OleDbConnection
Private Sub RefreshData()
If Not cnn.State = ConnectionState.Open Then
'-------------open connection-----------
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("select stdID as [StdIdTxt]," &
"Fname as [FnameTxt] ,Lname,BDy,age,gender,address,email,LNO,MNO,course" &
"from studentTB order by stdID", cnn)
Dim dt As New DataTable
'------------fill data to data table------------
da.Fill(dt)
'close connection
cnn.Close()
End Sub
Private Sub AddNewBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddNewBtn.Click
Dim cmd As New OleDb.OleDbCommand
'--------------open connection if not yet open---------------
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
'----------------add data to student table------------------
cmd.CommandText = "insert into studentTB (stdID,Fname,Lname,BDy,age,gender,address,email,LNO,MNO,course)" &
"values (" & Me.StdIdTxt.Text & "','" & Me.FnameTxt.Text & "','" & Me.LNameTxt.Text & "','" &
Me.BdyTxt.Text & "','" & Me.AgeTxt.Text & "','" & Me.GenderTxt.Text & "','" &
Me.AddTxt.Text & "','" & Me.EmailTxt.Text & "','" & Me.Hometxt.Text & "','" & Me.mobileTxt.Text & "','" & Me.Coursetxt.Text & "')"
cmd.ExecuteNonQuery()
'---------refresh data in list----------------
'RefreshData()
'-------------close connection---------------------
cnn.Close()
This insert error is nothing but a syntax error, there is no need for changing your code. please avoid reserved words like "password" form your database. This error is due to the field name password
The SQL string should look like this
sqlQry = "INSERT INTO tbl_user(username, password) VALUES(" & usernme & "', " & passwrd & ")"
The values usernme & passwrd aren't valid to the database.
Beyond that you really should look into using a Command object and parameters.

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!

how to save all record show in datagridview to the database

i have this code that will save only the top row of the datagridview,
can someone help me to modify this code so that it will save all the row in datagridview. im using vb 2010 and my database is ms access. thankyou in advance.
Try
Dim cnn As New OleDbConnection(conString)
query = "Insert into tblreportlog(EmpID,empname,department,empdate,timeinaM,timeoutam,lateam,timeinpm,timeoutpm,latepm,thw) values ('" & dgvReport.Item(0, dgvReport.CurrentRow.Index).Value & "', '" & dgvReport.Item(1, dgvReport.CurrentRow.Index).Value & "', '" & dgvReport.Item(2, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(3, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(4, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(5, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(6, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(7, dgvReport.CurrentRow.Index).Value & "', '" & dgvReport.Item(8, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(9, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(10, dgvReport.CurrentRow.Index).Value & "')"
cmd = New OleDbCommand(query, cnn)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
Catch ex As Exception
MsgBox("ERROR: " & ErrorToString(), MsgBoxStyle.Critical)
End Try
Working from what is shown and best practices injected, you should be working from a data source such as a DataTable e.g. if when presented the DataGridView to the user there are no rows then create a new DataTable, set the DataTable as the DataSource of the DataGridView then when you are ready to save these rows in the DataGridView cast the DataSource of the DataGridView to a DataTable and use logic similar to the following
Dim dt As DataTable = CType(DataGridView1.DataSource, DataTable)
If dt.Rows.Count > 0 Then
Using cn As New OleDb.OleDbConnection With {.ConnectionString = "Your connection string"}
' part field list done here
Using cmd As New OleDb.OleDbCommand With
{
.Connection = cn,
.CommandText = "Insert into tblreportlog(EmpID,empname,department) values (#EmpID,#empname,#department)"
}
' TODO - field names, field types
cmd.Parameters.AddRange(
{
{New OleDb.OleDbParameter With {.ParameterName = "#EmpID", .DbType = DbType.Int32}},
{New OleDb.OleDbParameter With {.ParameterName = "#empname", .DbType = DbType.Int32}},
{New OleDb.OleDbParameter With {.ParameterName = "#department", .DbType = DbType.String}}
}
)
Dim Affected As Integer = 0
cn.Open()
Try
For Each row As DataRow In dt.Rows
' this should not be a auto-incrementing key
cmd.Parameters("#EmpID").Value = row.Field(Of Integer)("FieldName goes here")
cmd.Parameters("#empname").Value = row.Field(Of Integer)("FieldName goes here")
cmd.Parameters("#department").Value = row.Field(Of String)("FieldName goes here")
Affected = cmd.ExecuteNonQuery
If Affected <> 1 Then
Console.WriteLine("Error message, insert failed")
End If
Next
Catch ex As Exception
'
' handle exception
'
' for now
MessageBox.Show("Failed with: " & ex.Message)
' decide to continue or not
End Try
End Using
End Using
End If
On the other hand, if there are new rows with current rows we cast the data source as above then check for new rows along with validation as needed.
For Each row As DataRow In dt.Rows
If row.RowState = DataRowState.Added Then
If Not String.IsNullOrWhiteSpace(row.Field(Of String)("CompanyName")) Then
Other options, utilize a DataAdapter or setup data via data wizards in the ide where a BindingNavigator is setup with a save button.
If it's important to get the new primary key back the method for all methods can do this too.
The following code sample is from this MSDN code sample that shows how to get a new key back using OleDb connection and command.
Public Function AddNewRow(ByVal CompanyName As String, ByVal ContactName As String, ByVal ContactTitle As String, ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Try
Using cn As New OleDb.OleDbConnection(Builder.ConnectionString)
Using cmd As New OleDb.OleDbCommand("", cn)
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName,ContactTitle) Values (#CompanyName,#ContactName,#ContactTitle)"
cmd.Parameters.AddWithValue("#CompanyName", CompanyName.Trim)
cmd.Parameters.AddWithValue("#ContactName", ContactName.Trim)
cmd.Parameters.AddWithValue("#ContactTitle", ContactTitle.Trim)
cn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function