I'm doing insert username and password into database in vb.net but it gives this error:
the error image
can someone take a look what cause it?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Amin\source\repos\Nando's\Nando's\user.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = "insert into user ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
MsgBox("Record added", MsgBoxStyle.Information)
End Sub
I change from this:
command = "insert into user ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
to this:
command = "insert into [user] ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
I just put a bracket at user and it is solved.
The bad thing is I was going back and forth between tutorial for days but neither of them solve it because the error was on the table name but it is finally solved. Thank you to Hursey for mentioning reserved words.
Related
I'm using this code to insert in database , but every time it inserts more than one row ,what is the problem ?
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
Dim com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
con.Open()
com.ExecuteNonQuery()
con.Close()
End Using
End Sub
Have you checked to see if your block of code is being called more than once? One quick way is to put a alert box inside so you can count the times it runs.
Well... there are lots of problems. The first of which is the potential for SQL Injection, you should be using named parameters. Another is that the line about Dim com As New... should also be in a Using clause.
However, nothing in that bit of code suggests that it is inserting more than 1 record. I suggest you put a break point on the ExecuteNonQuery line and see what's going on.
I have checked and hole the button click was executed twice , I have changed the code to this one and it has been solved , but I dont know why the click event is executed twice :
Dim i As Boolean = True
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
con.Open()
Using com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
If i = True Then
com.ExecuteScalar()
i = False
End If
End Using
con.Close()
End Using
End Sub
I get a catch exp as Exception Error in which says, data source is an invalid type, it must either be of the type IListSource, IEnumerable or IDataSource.
This error comes when I try to add a new record to a database through a gridview, so I get the data from database nicely into this gridview, therefore I do not understand that I get a catch exp as exception when the database is not unavailable.
The #thesli_number OleDbType.VarChar Value = thenumber is type of number in the db.
'Add new record to DB
Protected Sub AddNewTask(ByVal sender As Object, ByVal e As EventArgs)
Dim thecat As String = DirectCast(GridView1.FooterRow.FindControl("txttestcat"), TextBox).Text
Dim theinfo As String = DirectCast(GridView1.FooterRow.FindControl("txttestinfo"), TextBox).Text
Dim thenumber As String = DirectCast(GridView1.FooterRow.FindControl("txttestnumber"), TextBox).Text
Dim strSQL As String = ""
strSQL = "" & _
"INSERT INTO [TableTest] " & _
"([test_cat], [test_info], [test_number])" & _
"VALUES (#thesli_cat, #thesli_info, #thesli_number)"
Using conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
Try
conn.Open()
Dim cmd As New OleDbCommand(strSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#thesli_cat", OleDbType.VarChar).Value = thecat
cmd.Parameters.Add("#thesli_info", OleDbType.VarChar).Value = theinfo
cmd.Parameters.Add("#thesli_number", OleDbType.VarChar).Value = thenumber
GridView1.DataSource = cmd
GridView1.DataBind()
'MsgBox("Row(s) Added !! ")
Catch exp As OleDbException
If True Then
MsgBox("Error trying to add current record. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Critical)
End If
Catch exp As Exception
If True Then
MsgBox("Error the Database can be unavailable atm. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Information)
End If
End Try
End Using
End Sub
EDIT................EDIT.................EDIT...................EDIT
Ok i can now add data to the gridview, i can delete a record and i can add a new record.
But i cant get the update event to work, can u see whats wrong in this new code !?
'Update record
Protected Sub UpdateTask(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim theid = Convert.ToInt32(DirectCast(GridView1.FooterRow.FindControl("lbltestid"), Label).Text)
Dim thecat As String = DirectCast(GridView1.FooterRow.FindControl("lbltestcat"), Label).Text
Dim theinfo As String = DirectCast(GridView1.FooterRow.FindControl("lbltestinfo"), Label).Text
Dim thenumber As String = DirectCast(GridView1.FooterRow.FindControl("lbltestnumber"), Label).Text
Dim strSQL As String = ""
strSQL = "" & _
"UPDATE [TableTest] " & _
"SET [test_cat] = #thesli_cat, [test_info] = #thesli_info, [test_number] = #thesli_number " & _
"WHERE [test_id] = #thesli_id"
Using conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
Try
conn.Open()
Dim cmd As New OleDbCommand(strSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#thesli_id", OleDbType.Integer).Value = theid
cmd.Parameters.Add("#thesli_cat", OleDbType.VarChar).Value = thecat
cmd.Parameters.Add("#thesli_info", OleDbType.VarChar).Value = theinfo
cmd.Parameters.Add("#thesli_number", OleDbType.Integer).Value = thenumber
cmd.ExecuteNonQuery()
'MsgBox("Row(s) Updated !! ")
GridView1.EditIndex = -1
GetRecords()
Catch exp As OleDbException
If True Then
MsgBox("Error trying to add current record. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Critical)
End If
Catch exp As Exception
If True Then
MsgBox("Error the Database can be unavailable atm. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Information)
End If
End Try
End Using
End Sub
If the answer to your original question was answered in my comment above (posted below here in quotes), then you should mark this question as answered, then post an entirely new question so you get more accurate responses. This question no longer applies to your actual problem.
My answer which, in your comment, solved your original question:
That example (referring to the link in your comment above) does not directly assign an
OleDbCommand to the DataSource, because it
can't. If you look at the example the author passes the cmd variable
to the GetData function GetData(cmd), which more than likely executes
the stored procedure and returns a DataSource supported type (e.g.
IListSource, IEnumerable or IDataSource).
I am a newbie in using asp.net, I am getting a problem on how to refresh the GridView after the data is updated but it seems it's not working on my others pages. I have same code when I updated the supplier info and then the GridView1.Databind() is working but when I try to use this again on my other pages it doesn't work. Can you give an idea why is this happens?
Here is my code:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "UPDATE ProductTable SET ProductCode = ('" & lbl_productcode.Text & "'), ProductName = ('" & txt_prodname.Text & "'),ProductCategory =('" & lbl_category.Text & "'),Price =('" & txt_price.Text & "'), Quantity=('" & txt_qty.Text & "'), CategoryID=('" & lbl_catid.Text & "') WHERE ProductCategory = '" & TextBox1.Text & "'"
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("RECORD UPDATED", MsgBoxStyle.Information)
GridView1.DataBind()
Call clear()
End Sub
I do not see anywhere in your code where you actually set the DataSource of your GridView before you DataBind() it. Check it out!
UPDATE:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "UPDATE ProductTable SET ProductCode = ('" & lbl_productcode.Text & "'), ProductName = ('" & txt_prodname.Text & "'),ProductCategory =('" & lbl_category.Text & "'),Price =('" & txt_price.Text & "'), Quantity=('" & txt_qty.Text & "'), CategoryID=('" & lbl_catid.Text & "') WHERE ProductCategory = '" & TextBox1.Text & "'"
cmd.Connection.Open()
Me.GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
cmd.Connection.Close()
MsgBox("RECORD UPDATED", MsgBoxStyle.Information)
Call clear()
End Sub
Good luck!
this code works fine but its inserts the same data twice in sql db on just one button click . if i made some mistake plz let me know ..
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As New SqlCommand
Dim str As String
str = "insert into cmember(name,period,design,duty,quali,cont)values ('" & TextBox1.Text & "', '" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "', '" & TextBox5.Text & "','" & TextBox6.Text & "')"
If con.State = ConnectionState.Closed Then
con.Open()
End If
Try
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.CommandText = str
Catch ex As Exception
MsgBox(e.ToString)
End Try
If cmd.ExecuteNonQuery Then
Label1.Text = "entry saved"
con.Close()
Else
Label1.Text = "entry not saved"
End If
End Sub
I can't see the valid reason why it inserts twice a same record in current code snippet. May be a button is hit twice or you are refreshing a web page.
Off-the topic : Do not use hard coded SQL statement. Use parameterized query. (Read about SQL Injection)
str = "insert into cmember (name,period,design,duty,quali,cont) values
(#name,#period,#design,#duty,#quali,#cont)"
This might seem silly, but you're not double clicking the button, are you ?
Also, never use a Msgbox call in ASP - the messagebox will appear on the server, not on the browser, and it will block the thread until clicked. You're much better to create an ASP Label control and assign the text to that.
Also, the bit enclosed in a Try block is just settings and will never throw an error - the try block should be around the commands where you open the connection, and where you execute the query.
Your code is not appearing to insert this data in twice.
The best way to find out what exactly is happening is to run a trace through SQL Server Profiler. To do this you need to ensure you have ALTER TRACE permissions on the instance.
Is there a way to insert a dynamically generated datatable into mysql database in asp.net?
Sub OutputQty(ByVal dt As DataTable, ByVal AdID As Integer)
Dim sql As String = ""
Dim con As New SqlConnection(Utilities.DELcon)
Dim cmd As New SqlCommand(sql, con)
con.Open()
For Each row In dt.Rows
sql = "INSERT INTO DMQtyOutput (AdID, CompanyID, StoreNumber, DemandQty) VALUES ('" & row("AdID") & "','" & row("CompanyID") & "','" & row("StoreNumber") & "','" & row("DemandQty") & "')"
cmd.CommandText = sql
cmd.ExecuteNonQuery()
Next
con.Close()
End Sub