escaping apostrophes with parameter query not working - asp.net

I am trying to prevent from having to escape apostrophes in my string variables by using a parameterized query with a OleDbConnection, but it is not working. any help would be appreciated. I am trying to insert into an Access db and I keep getting those pesky html codes.
Any hep would be appreciated.
Dim pConn As New OleDb.OleDbConnection
pConn = New OleDbConnection(cb.ConnectionString)
Dim SqlString As String = "INSERT INTO Strings (Mlt_String_ID, Lng_ID, Strg_Name, Sht_Text, Lng_Text, Alt_Text) Values (#Mlt_String_ID,#Lng_ID,#Strg_Name,#Sht_Text,#Lng_Text,#Alt_Text)"
Using cmd As New OleDbCommand(SqlString, pConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Mlt_String_ID", Mlt_String_ID)
cmd.Parameters.AddWithValue("#Lng_ID", Lng_ID)
cmd.Parameters.AddWithValue("#Strg_Name", Strg_Name)
cmd.Parameters.AddWithValue("#Sht_Text", Sht_Text)
cmd.Parameters.AddWithValue("#Lng_Text", Lng_Text)
cmd.Parameters.AddWithValue("#Alt_Text", Alt_Text)
pConn.Open()
cmd.ExecuteNonQuery()
pConn.Close()
End Using

ou didn't describe what "not working" means. Can you provide more information? Are you getting an exception? What is the exception and stack trace?
In any event, the OleDb commands do not support named parameters. Use question marks instead:
Dim SqlString As String = "INSERT INTO Strings (Mlt_String_ID, Lng_ID, Strg_Name, Sht_Text, Lng_Text, Alt_Text) Values (?,?,?,?,?,?)"
And the parameters must be added in order.

Related

Execute Scalar to Label. Subquery returned more than 1 value

So I have a label which shows the username of the user. I've used this value to return their ID which I then attach to a label. I used execute scalar to do this because I wasn't sure how else to get a single value on a label.
This works fine. I then use the ID from the label and put it in another table. I can do this twice and then the page crashes saying...
"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."
However I don't understand. I don't pull anything from the second table on the page. I don't know why it would affect it. I feel like I've tried everything. Taking out the line that posts the ID to the label lets the page run but I need it there.
Label2.Text = User.Identity.Name
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String
connetionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True"
sql = "SELECT SupID FROM Supervisor WHERE (Email = #Email)"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
cmd = New SqlCommand(sql, cnn)
cmd.Parameters.Add(New SqlParameter("#Email", User.Identity.Name))
Dim supid1 As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
cmd.Dispose()
cnn.Close()
Label1.Text = supid1.ToString
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
This should return the first result for you. Also, it's a good idea to employ Using blocks for objects such as connections, commands, and readers.
Using cn = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True")
cn.Open()
Using cmd = New SqlCommand("SELECT SupID FROM Supervisor WHERE Email = #Email", cn)
cmd.Parameters.AddWithValue("#Email", User.Identity.Name)
Using dr = cmd.ExecuteReader
If dr.Read Then
Label1.Text = CInt(dr("SupID"))
End If
End Using
End Using
End Using
If you are not sure there are multiple rows for same email in that table, you can change the query to following, that will work for you with executescalar.
SELECT TOP 1 SupID FROM Supervisor WHERE (Email = #Email)
Horribly sorry! But yes you were right! There was another query going on in the background that I never noticed that was affecting it all. So sorry

VB.NET ORA-01745: invalid host/bind variable name

For the last 2 hours I was trying figure out why the parameter could not be bound (Well I know I was not using the "using" block. And I know System.Data.OracleClient is deprecated.) Please help me see what's wrong with the following code:
Dim nCount As Integer
sSQL = " SELECT COUNT(*) FROM USERS WHERE USER_ID = :UID "
Dim conn As OracleConnection = New OracleConnection(ConfigurationSettings.AppSettings("connString"))
conn.Open()
Dim cmd As OracleCommand = New OracleCommand(sSQL, conn)
cmd.CommandType = CommandType.Text
With cmd
.Parameters.Add(New OracleParameter(":UID", txtUserID.Text))
End With
Try
nCount = cmd.ExecuteScalar()
Catch ex As Exception
End Try
I have tried all variations I can find online: with or without colon in the Parameters.Add, Add or AddWithValue, Add in a parenthesis or create a new OracleParameter object then add it...Nothing seems to work.
But if I just hard-code the USER_ID in the query, remove the parameter.Add, it would return a value.
A HA!
UID is actually a reserved word in Oracle. Change your UID variable to something that is not a reserved word.
For me it seems that you missed something, while experimenting with different combinations.
This variant must work:
Dim nCount As Integer
sSQL = "SELECT COUNT(*) FROM USERS WHERE USER_ID = :UID"
Dim conn As OracleConnection = New OracleConnection(ConfigurationSettings.AppSettings("connString"))
conn.Open()
Dim cmd As OracleCommand = New OracleCommand(sSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("UID", OracleType.VarChar).Value = txtUserID.Text
nCount = cmd.ExecuteScalar()
Please try it ...
Do yourself a favor and at least look into ODP from Oracle. You'll need it with Microsoft finally pulls the plus on its OracleClient. The switch over to ODP is very easy.
In your situation, I'd leave off the parameter name. You're binding by position anyway.
The SQL syntax is also a little different in the Microsoft implementation. Use a ? to act as each placeholder. See http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracleparameter.aspx for further information.

correct syntax for VB web service code sql insert FOR XML AUTO, ELEMENTS?

I am having some trouble getting the correct syntax for a bit if code. I am using vb to insert data into a db and outputting the data as XML, here is the code
<WebMethod()> _
Public Function addTrack(ByVal tTitle As String, ByVal tAlbum As String, ByVal tGenre As String) As String
Dim conn As New SqlConnection("Data Source=MARTIN-LAPTOP\SQLEXPRESS;Initial Catalog=mp3_playlists;Integrated Security=True")
Dim sql As String = "INSERT INTO Tracks (trackTitle, trackAlbum, trackGenre) VALUES ('" & tTitle & "', '" & tAlbum & "', '" & tGenre & "') FOR XML AUTO, ELEMENTS"
conn.Open()
Dim cmd As New SqlCommand(sql, conn)
Dim track As String = cmd.ExecuteScalar()
conn.Close()
Return track
End Function
The code is for a ASP.NET web service, when I click invoke on the website i get the error Incorrect syntax near the keyword 'FOR'. If I remove FOR XML AUTO, ELEMENTS everything works find, db updates but I dont get the data to output as XML. I think the issue is with
the brackets required for the insert values because this issue does not occur if the SQL statement is a SELECT statement which has no brackets but i just cant figure out the correct syntax, thanks for your help
FOR XML AUTO is only used for SELECT statements. So, the issue is not your insert statement, it is your select statement, whereever that is.

SqlClient.SqlCommand Bombing Out

Still new to .NET, but this looks OK to me. I can't figure out what's going on. I'm trying to add 1 parameter to a SqlCommand. It is an integer in SQL Server, and I'm passing an integer to it.
It hangs on the Command.Parameters.Add(PolicyNo) code line and kicks out an "unable to process due to internal error".
I've also tried
Command.Parameters.AddWithValue("#PolicyNumber", PolicyNo)
But to no avail. It bombs out with the same error message. Here's the code:
Public Function GetPolicyObj(ByVal PolicyNo As Integer) As PolicyInfo Implements ILetterWriter.GetPolicyObj
Dim SQLcon As New SqlClient.SqlConnection
'Establish the connection
SQLcon.ConnectionString = "Data Source=Hosed;Initial Catalog=MyCat;User ID=Goofy;Password=OpenSesame;"
SQLcon.Open()
Using Command As New SqlClient.SqlCommand("sp_GetPolicyInfo", SQLcon)
Command.CommandType = CommandType.StoredProcedure
Command.Parameters.Add(PolicyNo) 'Bombs on this line
Command.Connection.Open()
Dim reader As SqlClient.SqlDataReader = Command.ExecuteReader
Any Ideas?
Thanks,
Jason
Have you tried creating the parameter like this:
Dim param as new SqlParameter()
param.ParameterName = "ParamName"
param.Value = PolicyNo
Command.Parameters.Add(param)
Not entirely sure if this is the problem should be, but you are not giving the parameter object a name, only passing the value which will thrown an exception, you have to give the parameter a name as well
Command.Parameters.Add(new SqlParameter("PolicyNo",PolicyNo))
Command.Parameters.Add() takes a SqlParameter object as its parameter. So you can't just send the integer.
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx
Try:
Command.Parameters.AddWithValue("#PolicyNo", PolicyNo);
Maybe you could try explicitly typing your parameter:
Command.Parameters.Add("#PolicyNumber", SqlDbType.Int)
Command.Parameters("#PolicyNumber").Value = PolicyNo
And make sure your parameter name and datatype match what's in the stored procedure.

Using an IN clause in Vb.net to save something to the database using SQL

I have a textbox and a button on a form.
I wish to run a query (in Vb.Net) that will produce a query with the IN Values.
Below is an example of my code
myConnection = New SqlConnection("Data Source=sqldb\;Initial Catalog=Rec;Integrated Security=True")
myConnection.Open()
myCommand = New SqlCommand("UPDATE dbo.Recordings SET Status = 0 where RecID in ('" & txtRecID.Text & "') ", myConnection)
ra = myCommand.ExecuteNonQuery()
myConnection.Close()
MsgBox("Done!", _
MsgBoxStyle.Information, "Done")
When I enter a single value it works but when I enter values with commas it throws an error:
"Conversion failed when converting the varchar value '1234,4567' to
data type int."
Could someone please help me to solve this or if there is an alternative way?
Many Thanks
Try removing the single-quotes you're wrapping the IN values in:
myCommand = New SqlCommand("UPDATE dbo.Recordings SET Status = 0 WHERE RecID IN (" & txtRecID.Text & ") ", myConnection)
If you were testing a STRING variable for multiple values, then those multiple values would need to be in quotes.
The reason your first attempt 'almost' worked was because you could also have generated your SqlCommand with each individual value in quotes.
I.E.
UPDATE dbo.Recordings SET Status = 0 where RecID IN ('1234', '5678')
In that case, T-SQL would have done an implicit conversion of each of the string values to INT,
which is what it was attempting to do when you gave it '1234, 5678' but that isn't decipherable as an INT.

Resources