I have a couple of queries that I need to run one to a linked server and one not like this
Dim InvestorLookup As String = "DECLARE #investor varchar(10), #linkedserver varchar(25), #sql varchar(1000) "
InvestorLookup += "SELECT #investor = '" & investor & "', #linkedserver = '" & db & "', "
InvestorLookup += "#sql = 'SELECT * FROM OPENQUERY(' +#linkedserver + ', ''SELECT * FROM db WHERE investor = ' + #investor + ' '')' EXEC(#sql)"
Dim queryInvestorLookup As SqlCommand = New SqlCommand(InvestorLookup , conn)
Dim BondNoDR As SqlDataReader = queryInvestorLookup.ExecuteReader()
Dim PasswordCheck As String = "DECLARE #investor varchar(10), #password varchar(20), #linkedserver varchar(25), #sql varchar(1000) "
PasswordCheck += "SELECT #investor = '" + investor + "', #password = '" + password + "', #server = '" + db2 + "', "
PasswordCheck += "#sql = 'SELECT * FROM #server WHERE investor = #investor AND password = ' + #password + ' '' EXEC(#sql)"
Dim queryPasswordCheck As SqlCommand = New SqlCommand(PasswordCheck, conn)
Dim PasswordDR As SqlDataReader = queryPasswordCheck.ExecuteReader()
As far as I can tell from debugging the queries both run as they should but I get the error
There is already an open DataReader associated with this Command which must be closed first.
Is it possible to run two queries in two different DataReaders. I need to later reference each DataReader and select values from each.
By default it´s not possible to have two SqlDataReader's open at the same time sharing the same SqlConnection object. You should close the first one (queryInvestorLookup) before calling the second (queryPasswordCheck).
This would be good from a design and performance point of view since a recommendation for .NET is that every unmanaged resource (like database access) is opened as later as possible and closed early as possible.
Another way would be to enable MARS but afaik it is only available for Sql2005 and up.
The third solution would be to use the same SqlDataReader to issue the two queries and then navigate through then using NextResults() method.
If the provider that you are using supports it, you can enable MARS (Multiple Active Result Sets) by adding MultipleActiveResultSets=True to the connection string that you are using.
By default you can't have to dataReaders open on the same connection. So you could get one result, stuff it in a DataTable and then get the other result. Or you could turn on MARS
ADO.NET Multiple Active Resut Sets
Related
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.
I'm programming an education website using asp.net vb.net and SQL Server. I have 4 stackholders, if any body log in in his profile he will see his information
If he wants to update them he just change the textboxes then click update
My problem is how to update.
I wrote a method to update but it always show me a syntax error in the query. I made sure there is no problem. I'm updating two tables and I made to sql statements!
My qustion is can I Insert instead of update?
If not: how to upade one record based on the session I have?
please help me
this my code
' Private Sub UpdateInfo(ByVal USER_ID As Integer)
'Dim User As Integer = USER_ID
'Dim sql1 As String = "UPDATE AdminCoordinatorInformation SET MobileNumber =" + tbmobile.Text + ", HomeNumber=" + tbhome.Text + ", AltRelation = " + DDLRelationShip.SelectedValue + ", AlTitle = " + DDLTitle.SelectedValue + ", AltName = " + tbemname.Text + ", AltMobile = " + tbemmobile.Text + " WHERE USER_ID = User)"
'Dim sql2 As String = "UPDATE DIP_USERS SET USER_Email=" + tbEmail.Text.Trim + " WHERE USER_ID = User)"
' Try
' Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("mydbConnectionString").ConnectionString)
' Dim cmd1 As New SqlCommand(sql1, conn)
' Dim cmd2 As New SqlCommand(sql2, conn)
' cmd2.Parameters.AddWithValue("#FirstName", tbname.Text)
' cmd2.Parameters.AddWithValue("#USER_PASSWORD", tbnewpassword.Text)
' cmd2.Parameters.AddWithValue("#USER_Email", tbEmail.Text)
' cmd1.Parameters.AddWithValue("#MobileNumber", tbmobile.Text)
' cmd1.Parameters.AddWithValue("#HomeNumber", tbhome.Text)
' cmd1.Parameters.AddWithValue("#AltRelation", DDLRelationShip.SelectedValue)
' cmd1.Parameters.AddWithValue("#AlTitle", DDLTitle.SelectedValue)
' cmd1.Parameters.AddWithValue("#AltName", tbemname.Text)
' cmd1.Parameters.AddWithValue("#AltMobile", tbemmobile.Text)
' conn.Open()
'Dim ra As Integer = cmd1.ExecuteNonQuery()
'Dim ra1 As Integer = cmd2.ExecuteNonQuery()
'cmd1.Dispose()
'cmd2.Dispose()
' conn.Close()
' Catch ex As Exception
' MsgBox(ex.Message)
' End Try
'End Sub
you have not specified your parameters in your query, you're directly concatenating the values of controls inside your query. And still you have added parameters.
Firstly, do not concatenate your sql query like that, its prone to SQL Injection.
construct your query like this:
Dim sql1 As String = "UPDATE AdminCoordinatorInformation SET
MobileNumber =#MobileNumber,
HomeNumber=#HomeNumber,
AltRelation = #AltRelation,
AlTitle = #AlTitle,
AltName =#AltName,
AltMobile = #AltMobile
WHERE USER_ID = #User"
Dim sql2 As String = "UPDATE DIP_USERS SET
USER_Email=#USER_Email
WHERE USER_ID = #User"
and also, add this parameter too
cmd1.Parameters.AddWithValue("#User", USER_ID)
cmd2.Parameters.AddWithValue("#User", USER_ID)
And one very important thing. you need to assign proper datatype to your columns in the query i.e.
remember these things.
txtBox.Text returns String value, you might need to convert it to Int32 using Convert.Int32 or you need to wrap it in single quote, based totally upon datatype of your column
Put parameters which you declare in your SQL Command query:
"UPDATE AdminCoordinatorInformation SET MobileNumber=#MobileNumber,HomeNumber=#homeNumber...
You get syntax error because your string data in sql query must be wrapped with "'".
"UPDATE AdminCoordinatorInformation SET MobileNumber='0987654321',....
Note: creating sql queries by concating query with user inputs ("...SET MobileNumber='" + txtbox.Text + "',...") is not good/dangerous practice because of SQL Injection
I'm having some trouble writing a query using variables. Here's my code
Dim bondnumber as String = "69836"
Dim PasswordCheck As String = "DECLARE #investor varchar(10),
#thepassword varchar(20), #linkedserver2 varchar(25), #sql varchar(1000) "
PasswordCheck += "SELECT #investor = '" & bondnumber & "',
#linkedserver2 = 'binfodev', "PasswordCheck += "#sql = 'SELECT * FROM ' +
#linkedserver2 + ' WHERE bondno = ''#investor'' ' EXEC(#sql)"
It doesn't seem to be passing the variables properly in the query and i'm not sure where i'm going wrong
any ideas?
What is the problem you are seeing specifically? More info would help.
What I can tell, is that you're code translates to a long line of SQL (substituting '69836' for bondnumber)
DECLARE #investor varchar(10), #thepassword varchar(20), #linkedserver2 varchar(25), #sql varchar(1000) SELECT #investor = '69836', #linkedserver2 = 'binfodev', #sql = 'SELECT * FROM ' + #linkedserver2 + ' WHERE bondno = ''#investor'' ' EXEC(#sql)
I'll bet if you execute that in a query window it will fail. Try adding ; at the end of each logical statement.
Have you considered just making this code a stored procedure and passing params to this? Code like this is pretty hazardous (SQL Injection), hard to read, and just a bit ugly in general.
Sample Stored Procedure Code:
CREATE PROCEDURE dbo.usp_MyStoredProcedure
#Param1 INT = NULL
AS
SELECT * FROM MyTable Where Col1 = #Param1
#Jamie - Well I personally tend to find it is much clearer to break things a part a little bit although its not technically necessary. I am just saying to build your parameter variables separately and then add them as parameterized (something like the following):
Dim sql As String = "SELECT * FROM #LinkedServer WHERE bondno = #BondNumber"
Dim c As New SqlConnection("Your Connection String Here")
Dim cmd As SqlCommand = c.CreateCommand()
With cmd
.CommandType = CommandType.Text
.CommandText = sql
.Parameters.Add(New SqlParameter("#LinkedServer", SqlDbType.VarChar)).Value = "binfodev"
.Parameters.Add(New SqlParameter("#BondNumber", SqlDbType.VarChar)).Value = "69836"
End With
Dim dt As New DataTable
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
I have a web application and on page is an update page to update some profile information. Below is the code I am using to update the table. But I think it is wrong. Does anything stick out? The connection string works cause it is used to read the database to get the profile information, I just removed it due to it containing password/login info for the db.
player is the class of properties that contains player information and ds is the dataset, but I would like to update the database itself online...
Dim connectionString As String = ""
Dim GigsterDBConnection As New System.Data.SqlClient.SqlConnection(connectionString)
GigsterDBConnection.Open()
Dim updatetoursql As String = "UPDATE PLAYERS SET FIRSTNAME = '" & player.FIRSTNAME & "', LASTNAME = '" & player.LASTNAME & "', ADDRESS = '" & player.ADDRESS & "', CITY = '" & player.CITY & "', ZIP = '" & player.ZIP & "', PHONE = '" & player.PHONE & "', EMAIL = '" & player.EMAIL & "', REFFEREDBY = '" & player.REFEREDBY & "' "
updatetoursql = updatetoursql & "PLAYERID = '" & player.PLAYERID & "';"
Dim cmd As New System.Data.SqlClient.SqlCommand(updatetoursql, GigsterDBConnection)
Dim sqlAdapter As New System.Data.SqlClient.SqlDataAdapter(cmd)
sqlAdapter.Update(ds, "PLAYERS")
I think the issue is something the 3 last lines of the code. am I doing it right or is their a better way?
Thanks
Well, apart from the glaring SQL injection issues waiting to bite you ..... (hint: use parametrized queries instead of concatenating together your SQL statement!!)
Dim cmd As New SqlCommand(updatetoursql, GigsterDBConnection)
Dim sqlAdapter As New SqlDataAdapter(cmd)
The problem here is: if you call the SqlDataAdapter constructor this way, what you're passing in is the select command (of the data adapter) - not the update command!
You need to do it this way:
Dim cmd As New SqlCommand(updatetoursql, GigsterDBConnection)
Dim sqlAdapter As New SqlDataAdapter()
sqlAdapter.UpdateCommand = cmd;
Now you've associated your UPDATE statement with the SqlDataAdapter.UpdateCommand and now it should work.
About the SQL injection: I'd strongly recommend using parametrized queries all the time - at least in production code. So instead of concatenating together your query, use this:
Dim updatetoursql As String =
"UPDATE PLAYERS SET FIRSTNAME = #FirstName, LASTNAME = #LastName, " &
"ADDRESS = #Address, CITY = #City, ZIP = #Zip, PHONE = #Phone " &
"EMAIL = #EMail, REFFEREDBY = #ReferredBy, PLAYERID = #PlayerID"
and then before you execute the command or the SqlDataAdapter.Update statement, set those parameters to the values you have. This is much safer and gives you less headaches and possibly even speed improvements (if that single Update query is only cached once in SQL Server memory).
Also, why go the long and complicated way of a SqlDataAdapter at all??
After you've created the SqlCommand and set all the parameters, just call cmd.ExecuteNonQuery(); and you're done!
Dim cmd As New SqlCommand(updatetoursql, GigsterDBConnection)
// set up the parameters here.....
cmd.Parameters.AddWithvalue("#FirstName", FirstName);
... etc.
// just call ExecuteNonQuery - and you're done!
cmd.ExecuteNonQuery();
The big thing that jumps up at me is how open to SQL Injection attacks this code is.
You should not build a SQL string in this manner, but use parameterized queries.
Other then that, you are constructing your adapter incorrectly, as the constructor will take the select command, not the update command. Create the command with the parameterless constructor then assign the command you have created to the UpdateCommand property.
I have this code:
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 = "UPDATE tblAccounts balance = " & CDbl(balance + value) & " WHERE(accountID = " & accountID & ")"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.ExecuteNonQuery()
However, an exception is thrown, when I run it:
Syntax error in UPDATE statement.
I tried to run a similar statement in Access and it works fine.
I think the missing is SET.
Try: UPDATE table SET field = newvalue WHERE criteria;
Just modify:
sql = "UPDATE tblAccounts SET balance = " & CDbl(balance + value) & " WHERE(accountID = " & accountID & ")"
http://office.microsoft.com/en-us/access/HA100765271033.aspx
The SQL Statement definitely is missing the SET keyword. Also, I suggest you to brush up on parameterized query:
Dim sql As String = "UPDATE tblAccounts " & _
"SET balance = ? " & _
"WHERE(accountID = ?)"
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.Parameters.Add("Balance", CDbl(balance + value))
cmd.Parameters.Add("AccountId", accountID
cmd.ExecuteNonQuery()
This way, not only is the SQL Statment is clearer, it help prevents possible SQL injection attacks.
You are missing SET as part of UPDATE.
It should be UPDATE tablename SET fieldname = ... WHERE [criteria].
On a side note, you are using classic asp style code inside asp.net. I will suggest reading some docs on ASP.net and how to design applications in a layered manner.
A good start is here: Enterprise Library's Data Access Application Block
Link: https://web.archive.org/web/20210612110113/https://aspnet.4guysfromrolla.com/articles/030905-1.aspx