Parsing Date from VB.NET for SQL INSERT - asp.net

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.

Related

8000 character limit in ASP Classic / SQL Server

I am trying to do an update on a table in SQL Server 2008 R2, but the column writes only 8000 characters.
The column's datatype is set to text, but I have already tried to change to varchar(max) with no success.
I also used the cast('variable' as text) and cast('variable' as varchar(max)), also unsuccessfully.
When doing the same update by the SQL console (I made a response.write on the screen, copied and pasted it) or inserted more than 8000 characters manually, it works (through Microsoft Visual Studio).
sql_Up = "UPDATE ABVC_Eventos SET titulo_eve = '" & Strip(Evento) & "', cod_sup_eve = '" & Strip(cod_sup_eve) & "', cod_sup2_eve = '" & Strip(cod_sup2_eve) & "', texto_eve = CAST('" & Strip(texto_eve) & "' AS TEXT), WHERE id_eve = '" & Strip(Cod_Evento) & "'"
set Rs_sqlUp = bco.Execute(sql_Up)
The 'Strip' function is for sanitization.

Visual Basic code from Microsoft Access does not work

Private Sub cmdAdd_Click()
'add data to table
CurrentDb.Execute "INSERT INTO Products(ProductCode, ProductName, Category, UnitPrice, UnitCost, QuantityInStock, SupplierCode) " & _
" VALUES (" & Me.txtProductCode & " , '" & Me.txtProductName & "' , '" & Me.cboCategory & "' , '" & Me.txtUnitPrice & "' , '" & Me.txtUnitCost & "' , '" & Me.txtQuantityInStock & "' , '" & Me.cboSupplierCode & "')"
'refresh data on list of form
ProductsSub.Form.Requery
End Sub
the code above is suppose to record the data that has been input from the interface, but it does not do anything. The same format of code was used in a different form and it worked. Really weird, but i don't how it was possible.
You'll need to debug this. One of the values you are referencing visa the Me object is not resolving. Place a breakpoint on the CurrentDB.Execute command, and hover over each Me reference (i.e. Me.txtProductCode) to make sure it is obtaining the correct value for the insert. If you have moved this to a library, you may want to use CodeDB.Execute instead of CurrentDB.Execute. I would also check the table to see if the actual INSERT is working as there may be an issue with the Requery event.

Entering each row of datagrid into SQL database

I'm attempting to take a column from each row of my datagrid and enter it into an SQL database. Having all sorts of problems/errors making it work.
This is the most current version:
For i = 0 to agentGridView.Rows.Count - 1
varAgt = agentGridView.Rows(i).Cells(1).Text
strSQL = "INSERT INTO tblAgentVisitAgents (VisitID, AgtID)" & _
" Values (" & _
VisitID.Text & "," & _
varAgt & ")"
strSQL = Utils.replaceChars(strSQL)
DAL.ExecNonQuery(strSQL, CommandType.Text)
Next
EDIT: The issue is that my cell(1) is a hidden field. When I make it visible, the entry form works. When it's hidden, it won't enter anything and thus gives me a syntax error. Is there a way I can use a hidden field for entry purposes?
You need to use Text instead of Value . Like following.
varAgt = agentGridView.Rows(i).Cells(1).Text instead of varAgt = agentGridView.Rows(i).Cells(1).Value
But if you have that control in a Label, then you need to typecast to label and then use Text. E.g.
varAgt = CType(agentGridView.Rows(i).Cells(1).FindControl("controlID"),Label).Text -- replace controllID with required label id.
Source - http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
Here's what I went with:
Front:
<asp:GridView ID="agentGridView" DataKeyNames="agentName,agentValue" ... />
Back:
For i = 0 to agentGridView.Rows.Count - 1
varAgt = agentGridView.DataKeys(i).Values("agentValue").ToString
strSQL = "INSERT INTO tblAgentVisitAgents (VisitID, AgtID)" & _
" Values (" & _
VisitID.Text & "," & _
varAgt & ")"
strSQL = Utils.replaceChars(strSQL)
DAL.ExecNonQuery(strSQL, CommandType.Text)
Next
Source (for C#): Hide BoundField's but still be able to get values with C#

sql subquery syntax asp.net

I am trying to excute this sql query
Dim str As String = "UPDATE table1 SET " & _
"number = '" & strc & "'," & _
"code = '" & "123" & "'," & _
"line= '" & dd1.text & "'," & _
"sellr = '" & txtrun.text & "'," & _
"endu= '" & txtex1.value+txtex2.value & "'" & _
"WHERE number IN (select table1.number" & _
"FROM table1 INNER JOIN table2 ON table1.number = table2.number" & _
"WHERE ((table1.username)='" & session("username") & "' AND (table1.pass)='" & session("pass") & "' AND (table2.sellnum)='" & session("sellnum") & "'));"
there is a Syntax error in query expression and this is te first time I am using nested subquery
all the field are getting String values
So if someone can tell me what is the right approach to write this query I will be very grateful
You're missing spaces after table1.number and table2.number fields in the subquery.
I don't know where you're using this query, but you might want to read about SQL injection. When you stick strings together to build SQL, your code may be vulnerable to malicious users who put SQL code into the fields of your application.

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 " _

Resources