update data where IN list asp.net - asp.net

Dim nilx As String = textbox1.text --> (example. data like this. "10001,010001")
Using koneksi As New SqlConnection(stringkoneksi)
koneksi.Open()
Dim perintah As SqlCommand = koneksi.CreateCommand
perintah.CommandText = "update mytabledata set rumus='" & TextBox2.Text & "'
where code in (" & nilx & ") "
perintah.CommandType = CommandType.Text
perintah.ExecuteNonQuery()
koneksi.Close()
error when execute
Conversion failed when converting the nvarchar value '123test' to data type int
because in mytabledata there is code 123test, if i delete code 123test running well
so how to update data where code in (" & nilx & ")
error when execute
Conversion failed when converting the nvarchar value '123test' to data type int
because in mytabledata have code 123test, if i delete code 123test running well
so how to update data where code in (" & nilx & ")
if i have data nilx = "10001,010001,9912AA,1123BC"

Your codes in nilx must be in single quotes:
"'10001','010001','9912AA','1123BC'"
Also, use parameterized queries SQL Injection And Parameterized Queries. Don't just concatenate TextBox2.Text in your commands.

Related

second ExecuteReader() doesn't work

I have a code which checks the validity of user and then, if a user is valid it inserts certain values in the database.
My problem is when After I query my database to check if a user is valid and after that i try to pass the additional value to its account the flow stops when I invoke ExecuteReader() for the second time.
There is no error, or anything like that. I tried to substitute ExecuteReader() with ExecuteNoneQuery but still it's not working. I tried all the query in mysql command prompt they are working perfectly. I really can't understand what am I doing wrong there. Can anyone help me please?
Here is the code:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE SE_ID = " & Id.Text
Dim smd = New MySqlCommand(stquery, myconn)
Dim myreader = smd.ExecuteReader()
If Not myreader.HasRows Then
errorUser.Visible = True
Else
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
Dim Myreader2 As MySqlDataReader
'smd.ExecuteNonQuery()'
'THE CODE STOPS HERE'
Myreader2 = smd2.ExecuteReader()
'Myreader2.Read()'
MsgBox("The BACKUP INFORMATION HAS BEEN SAVED")
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
Because your second query is an update, not a select, you need to execute it using the ExecuteNonQuery method. Your commented-out code shows an attempt to call ExecuteNonQuery but on the wrong command object (smd when it should be smd2). Try something like this instead:
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd2.ExecuteNonQuery()
The ExecuteNonQuery method returns the number of rows updated as an int value, so you can capture it if it's valuable to you. In your case it's probably not, but here's how you'd check anyway:
int rowsAdded = smd2.ExecuteNonQuery();
if (rowsAdded == 1) {
// expected this
} else {
// didn't expect this
}
Finally, concatenating strings to build SQL commands can leave you vulnerable to SQL Injection attacks. Please take a look at using parameterized queries. There's a decent example here.
If you want to execute nested Reader, you have to create another connection. You need somethig like
smd2 = New MySqlCommand(stquery2, myconn2)' myconn2 is another connection
OR
Set "MultipleActiveResultSets=True in your connection string.
Also, use ExecuteNonQuery() for Inserting
Dim name As String = myreader("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES ('" & name & "', '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd.ExecuteNonQuery()
Please use Parameterized query to avoid SQL Injection
The logic is that you need to close your first reader (myreader) before executing another reader (MyReader2) on the same connection.

Parsing Date from VB.NET for SQL INSERT

I have a web app with a form that I am trying to pass to an ASP.NET server (using VB.NET) and then on to a MS SQL Server table. The form uses a jQuery datepicker in several textboxes and formats them as MM/dd/yyyy. The form fields are then passed through a PageMethod to the web server which takes the various field values and combines them into a SQL UPDATE command.
I am constantly getting the following error whenever I try to execute the SQL command:
Conversion failed when converting date and/or time from character string.
Here is the code on the server:
Using myConn As New System.Data.SqlClient.SqlConnection(CString.ConnectionString)
myConn.Open()
Dim cmd As New System.Data.SqlClient.SqlCommand("UPDATE table " & _
"SET type = '" & type & "', " & _
"target = '" & "#target" & "', " & _
"patient = '" & patient & "', " & _
"dob = '" & "#dob" & "' " & _
"WHERE serial = '" & serial & "'", myConn)
cmd.Parameters.Add(SqlParameter("#target", Data.SqlDbType.Date))
cmd.Parameters.Add(SqlParameter("#dob", Data.SqlDbType.Date))
If target = "" Then
cmd.Parameters("#target").Value = Data.SqlTypes.SqlDateTime.Null
Else
cmd.Parameters("#target").Value = target
End If
If dob = "" Then
cmd.Parameters("#dob").Value = Data.SqlTypes.SqlDateTime.Null
Else
cmd.Parameters("#dob").Value = dob
End If
cmd.ExecuteNonQuery()
End Using
Note: I've tried about twenty different ways of parsing the dates, converting them to dates, changing around the formats and none of it has worked.
Note 2: The conditional statements at the end are simply to prevent empty date fields from being stored in the SQL DB as "1/1/1900", but rather as an actual SQL NULL value. From debugging though, it seems that this is not the issue - it is when there is an actual value that the error is fired.
If anyone can see what I'm doing wrong and how I might fix it, it would be greatly appreciated. Thanks in advance for your help!
You are mixing up your parameterized and non-parameterized parts (why aren't you parameterizing everything?)
Dim cmd As New System.Data.SqlClient.SqlCommand("UPDATE table " & _
"SET type = '" & type & "', " & _
"target = #target, " & _
"patient = '" & patient & "', " & _
"dob = #dob " & _
"WHERE serial = '" & serial & "'", myConn)
Are you including time? DateTime fields require date and time.

ASP.net SQL database amend existing string field data using command parameters

I am trying to maintain a log field (fldUserLog ) of my database table so that when updating each raw, the log field will be amended with given log string.
Log string
strUserLog = "Added by : " & Session("auth_Id") & " at " & Now() & " from IP " &
Request.ServerVariables("REMOTE_ADDR") & vbCrLf
and I am using SQL command parameters to UPDATE query. as follows
strSQLQuery = "UPDATE myTable SET " _
& "fldTitle = #xTitle, " _
& "fldDesc = #xDesc, " _
& "fldUserLog = fldUserLog + #xUserLog " _
& "WHERE fldId = #xId ;"
strMessage = "updated"
ObjAddDB.setCommand(strSQLQuery)
With ObjAddDB
.setParameters("#xTitle", frmTitle.Text)
.setParameters("#xDesc", frmDesc.Text)
.setParameters("#xUserLog", strUserLog)
.setParameters("#xId", MyItemId)
End With
Please note that setCommand and setParameters are my own methods I am using in my database.vb class file.
I get following error when its executed
Exception Details:
System.Data.SqlClient.SqlException:
Incorrect syntax near 'fldUserLog'.
please help me to use my UPDATE query to amend existing data with command parameters.
If the format of the fldUserLog field value contains spaces, you need to embrace the value with [ ] ..
& "fldUserLog = [fldUserLog #xUserLog] " _
I guess what you may want to write is the following:
& "fldUserLog = #xUserLog " _

Web form is not updating tables, why?

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.

Writing an update query in asp.net (access database) (visual basic)

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

Resources