I'm adding a record like this:
Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])" & _
" VALUES ('" & firstName & "', '" & lastName & "', '" & address & _
"', '" & city & "', '" & province & "', '" & zip & "', '" & phone & "', '" & username & "', '" & password & "');"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.ExecuteNonQuery()
odbconBanking.Close()
The primary key is an autonumber field called UserID. So, how do I get the primary key of the record I just inserted?
Thanks.
I believe a parameterized query would look something like this:
Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])" & _
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
//Add Params here
cmd.Parameters.Add(new OdbcParameter("#FirstName", firstName))
cmd.Parameters.Add(new OdbcParameter("#LastName", lastName))
//..etc
//End add Params here
cmd.ExecuteNonQuery()
Dim newcmd As New OleDbCommand("SELECT ##IDENTITY", odbconBanking)
uid = newcmd.ExecuteScalar
odbconBanking.Close()
My syntax might be a bit off as I am more accustomed to using the Sql Server library and not the Odbc library, but that should get you started.
"SELECT ##IDENTITY" just after the insertion should work with Microsoft.Jet Provider.
You'll want to add
;select scope_identity();
after your query, and run executeScalar to get the value back.
Also, on a completely unrelated note, you really should change your code to use parameterized queries so you don't get caught with SQL injection attacks, or crashes due to inproperly escaped strings concatenated into your sql statement.
Got it. Here's how the above code looks now:
Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])" & _
" VALUES ('" & firstName & "', '" & lastName & "', '" & address & _
"', '" & city & "', '" & province & "', '" & zip & "', '" & phone & "', '" & username & "', '" & password & "');"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.ExecuteNonQuery()
Dim newcmd As New OleDbCommand("SELECT ##IDENTITY", odbconBanking)
uid = newcmd.ExecuteScalar
odbconBanking.Close()
The simplest way would be to generate your uniqueIdentifier value at the code level, add it to your string and send it to the server.
Dim sql As String, _
myNewUserId as variant
myNewUserId = stGuidGen 'this function will generate a new GUID value)'
sql = "INSERT INTO tblUsers ( userId, LastName)" & _
" VALUES ('" & myNewUserId & "','" & LastName);"
You can check a proposal for the stGuidGen guid generating code here.
This client-side technique is clear, clean and usefull
Related
I have encountered this "Invalid attempt to call Read when the reader is closed." error and I have tried to solve it for so many times. I think the connection is open but it still shows this error. Can somebody tell me why?
Here is the code:
Dim ConnComName As String
Dim sqlConnComName As SqlConnection
Dim sqlCmdComName As SqlCommand
Dim sqlComName As String
ConnComName = ConfigurationManager.ConnectionStrings("ConnString").ConnectionString
sqlComName = "Select COUNT(*) from TicketDetails where Company = '" & Company.SelectedValue & "' AND Priority = '" & Priority.SelectedValue & "' AND Application = '" & Application.SelectedValue & "' AND Creator = '" & Creator.Text & "' AND Status = '" & Status.SelectedValue & "' AND Module = '" & [Module].SelectedValue & "' AND Category = '" & Category.SelectedValue & "' AND IssueType = '" & IssueType.SelectedValue & "' AND IssueDescription = '" & IssueDescription.Text & "' "
sqlConnComName = New SqlConnection(ConnComName)
sqlConnComName.Open()
sqlCmdComName = New SqlCommand(sqlComName, sqlConnComName)
Dim sqlReader_ComName As SqlDataReader = sqlCmdComName.ExecuteReader()
While sqlReader_ComName.Read()
If sqlReader_ComName.GetValue(0) < 1 Then
ElseIf sqlReader_ComName.GetValue(0) > 0 Then
Dim CompanyName As String
Dim ConnComName01 As String
Dim sqlConnComName01 As SqlConnection
Dim sqlCmdComName01 As SqlCommand
Dim sqlComName01 As String
ConnComName01 = ConfigurationManager.ConnectionStrings("ConnString").ConnectionString
sqlComName01 = "Select Company from TicketDetails Where Company = '" & Company.SelectedValue & "' AND Priority = '" & Priority.SelectedValue & "' AND Application = '" & Application.SelectedValue & "' AND Creator = '" & Creator.Text & "' AND Status = '" & Status.SelectedValue & "' AND Module = '" & [Module].SelectedValue & "' AND Category = '" & Category.SelectedValue & "' AND IssueType = '" & IssueType.SelectedValue & "' AND IssueDescription = '" & IssueDescription.Text & "' "
sqlConnComName01 = New SqlConnection(ConnComName01)
sqlConnComName01.Open()
sqlCmdComName01 = New SqlCommand(sqlComName01, sqlConnComName01)
Dim sqlReader_ComName01 As SqlDataReader = sqlCmdComName01.ExecuteReader()
While sqlReader_ComName01.Read()
CompanyName = sqlReader_ComName01.GetValue(0)
' end while ComName01
End While
sqlReader_ComName01.Close()
sqlCmdComName01.Dispose()
sqlConnComName.Close()
End If
End While
sqlReader_ComName.Close()
sqlCmdComName.Dispose()
sqlConnComName.Close()
As has been said in the comments, the reason you are getting the error is because you are using a shared SqlConnection, which you close at the end of your inner loop, although there is actually no good reason to share a connection object here; .NET uses connection pooling behind the scenes, so there is little or no downside to creating new connection objects for every command, and it can often save confusion like this. You should also use Using blocks to ensure that all your managed resources are disposed of correctly and at the right time. Finally, and I can't stress this enough, use Parameterised queries, your code is vulnerable to injection, malformed SQL, type errors and will be unable to make use of query plan caching.
Although you have two loops in your code, all you ever do in those loops is to assign a value to a string:
While sqlReader_ComName01.Read()
CompanyName = sqlReader_ComName01.GetValue(0)
End While
So with every inner and outer loop, you overwrite the previous value, making all loops other than the last completely pointless. Since your SQL has no order by, you also have no idea which order the results will come in, so the "last" record could be any record here.
You don't need two loops here, if you only want a single value from the database, just select single value, there is no point returning 500 records if you are only going to use one.
So with all these changes your code might look something like this (forgive any syntax errors, it is about 8 years since I last wrote any VB.net)
Dim CompanyName As String
'Change SQL to only select 1 record, use an order by, and use parameters
Dim sql As String = "Select TOP (1) Company from TicketDetails Where Company = #Company AND Priority = #Prioirty AND Application = #Application AND Creator = #Creator AND Status = #Status AND Module = #Module AND Category = #Category AND IssueType = #IssueType AND IssueDescription = #IssueDescription ORDER BY Company"
' Create new conneciton in Using block
Using connection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnString").ConnectionString)
'Create new command in using block
Using command As SqlCommand = New SqlCommand(sql, connection)
'Add parameters to command, change your data types and lengths as necessary
command.Parameters.Add("#Company", SqlDbType.VarChar, 50).Value = Company.SelectedValue
command.Parameters.Add("#Priority", SqlDbType.VarChar, 50).Value = Priority.SelectedValue
command.Parameters.Add("#Application", SqlDbType.VarChar, 50).Value = Application.SelectedValue
command.Parameters.Add("#Creator", SqlDbType.VarChar, 50).Value = Creator.Text
command.Parameters.Add("#Status", SqlDbType.VarChar, 50).Value = Status.SelectedValue
command.Parameters.Add("#Module", SqlDbType.VarChar, 50).Value = [Module ].SelectedValue
command.Parameters.Add("#Category", SqlDbType.VarChar, 50).Value = Category.SelectedValue
command.Parameters.Add("#IssueType", SqlDbType.VarChar, 50).Value = IssueType.SelectedValue
command.Parameters.Add("#IssueDescription", SqlDbType.VarChar, 50).Value = IssueDescription.Text
'Open the connection
connection.Open()
'Create the data reader
Using reader As SqlDataReader = command.ExecuteReader()
'If the reader.Read() method returns true, then there is a record, so read it and assign it to the variable
If reader.Read()
CompanyName = reader.GetString(0);
End If
End Using
End Using
End Using
Private databaseConnector As DatabaseConnector
Dim fulltxtSQL As String
DatabaseConnector = New DatabaseConnector
Try
fulltxtSQL = "insert into [user-table] (username, password) VALUES ('" & UserName.Text & "','" & Password.Text & "')"
DatabaseConnector.RunSqlNonQuery(fulltxtSQL)
If DatabaseConnector.RunSqlNonQuery(fulltxtSQL) = True Then
MsgBox("thank you for registering ", vbInformation, Title.Trim)
Response.Redirect("Default.aspx")
Exit Sub
Else
MsgBox(MsgBox("There has been a error in your registering", vbInformation, Title.Trim))
End If
Catch ex As Exception
MsgBox(ex.Message.Trim, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Me.Title.Trim)
Exit Sub
End Try
End Sub
am trying to get the data from textbox to the database table.
syntax error in insert into statement the connection to the database works fine but when it reaches the insert into statement i get the error
Try this
INSERT INTO [user-table] ([username],[password]) VALUES('" & UserName.Text & "','" & Password.Text & "')"
You query contains special character such as user,table and password so it will give error. So what you need to do is to put such characters in paranthesis [].
Also you should use parameterized query.
try using this command
cmd = New System.Data.OleDb.OleDbCommand("INSERT INTO [user-table] ([username],[password]) VALUES('" & UserName.Text & "','" & Password.Text & "')", con)
if your table name contains such special charaters then use square brackets.
While executing the following code in ASP.NET with VB, I am getting the error "No data exists for the row/column."
Dim hdnuserid = e.CommandArgument
If e.CommandName = "additem" Then
' First, see if the product is already in the vendor_catalog table
Dim dr, dr2, username
dr = connection.returnsqlresult("SELECT * FROM vendor_users where vendor_id = '" & Request("vendor_id") & "' AND userid = '" & hdnuserid & "'")
If dr.hasrows() Then
dr.read()
Response.Write("<script type=""text/javascript"">alert(""User already assigned to this vendor."");</script>")
Else
dr2 = connection.returnsqlresult("SELECT * FROM users WHERE userid = '" & hdnuserid & "'")
Response.Write(hdnuserid)
If dr2.hasrows() Then
dr2.read()
username = dr("username")
connection.executesql("INSERT INTO vendor_users(userid, vendor_id, username) VALUES('" & hdnuserid & "','" & Request("vendor_id") & "','" & username & "')")
'ScriptManager.RegisterStartupScript(Me, GetType(Page), "itemsadded", "window.opener.__doPostBack('__Page', 'populate_usergrid');window.close();", True)
Else
Response.Write("<script type=""text/javascript"">alert(""User does not exist."");</script>")
End If
dr2.close()
End If
dr.close()
Else
End If
I have checked that the columns exist in my tables, and also checked the select * from users statement in SQL directly with a hard coded value and I see the result I expect. I'm not sure why I am getting this error. The error is being thrown on the username = dr("username") line.
Any assistance in this would be very helpful.
JV
I think you have a bit of a typo. Change
username = dr("username")
to
username = dr2("username")
Shouldnt the reader object be dr2 instead of dr? since dr doesnt have any rows, dr("username") wouldnt be accessible.
username = dr2("username")
using ASP.NET & VB.NET i trying to update the user password, where it is equals to the sessionID
Database using is SQL Local.
here is the vb .net code
Dim pass As String
pass = tboxConFirmPass.Text
Dim connce As SqlCeConnection = New SqlCeConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ToString())
connce.Open() 'make the connection to DB
Dim sqlCommand As String = "UPDATE [tbCustomer] SET [Password] = ('" _
+ tboxConFirmPass.Text + "', '" + "WHERE [CustomerID] = #CustomerID" + "')"
Dim cmd As SqlCeCommand = New SqlCeCommand(sqlCommand, connce)
cmd.ExecuteNonQuery()
connce.Close()
MsgBox("Your Password has been chaged.")
End Sub
here is the SqlDataSource
UpdateCommand="UPDATE [tbCustomer] SET [Password] = #Password WHERE [CustomerID] = #CustomerID">
Error = There was an error parsing the query. [ Token line number = 1,Token line offset = 42,Token in error = , ]
Right, your query needs to be changed thus:
Dim sqlCommand As String = "UPDATE [tbCustomer] SET [Password] = '" _
& Replace(tboxConFirmPass.Text, "'", "''") & "' WHERE [CustomerID] = #CustomerID"
I've sorted your brackets and quotes mismatches out, changed the string concatenation operator to & and put an escape in to reduce the possibility of SQL injection vulnerability (if someone puts a single quote in their password, your query will no longer fall over, or worse).
To set a value for #CustomerID you need to add a SQL Parameter to the command object. If you don't give it a value you'll get the error mentioned in your comment. Alternatively you can concatenate the value like you do with the password:
Dim sqlCommand As String = "UPDATE [tbCustomer] SET [Password] = '" _
& Replace(tboxConFirmPass.Text, "'", "''") & "' WHERE [CustomerID] = " & CustomerID
Note that you will need to use a variable that is initialised with the ID of the customer whose password is being changed.
When inserting data into a database, the following error occurs
"Excepted end of statement"
sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) VALUES ('" & Email & "', '" & First Name & "','" & Last Name & "','" & Comments & "')"
objConn.Execute sqlstr
Try using single-word identifiers for your first-name and last-name variables:
sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) " & _
" VALUES ('" & Email & "', '" & FirstName & "','" & LastName & "','" & Comments & "')"
objConn.Execute sqlstr
Assuming you've got variables with those names in your VBScript, that'll solve your current problem with Expected end of statement.
Your second problem is your code's vulnerability to SQL injection.
To help fix that problem, see:
Classic ASP SQL Injection Protection
http://www.stardeveloper.com/articles/display.html?article=2008112501&page=1
You might have single quote in one of the values, resulting in invalid SQL. You have to escape single quotes, though better rewrite your code to use parameters instead.
sqlstr = "INSERT INTO tblContact (Email, FirstName, LastName, Comments) " & _
" VALUES ('" & Replace(Email, "'", "''") & "', '" & Replace(FirstName, "'", "''") & "', '" & Replace(LastName, "'", "''") & "', '" & Replace(Comments, "'", "''") & "')"
objConn.Execute sqlstr