Preventing escaping apostrophes with parameter query not working - sql

I am trying to prevent from having to escape apostrophes in my string variables by using a parameterized query with a SqlConnection, but it is not working. any help would be appreciated.
UPDATED: this is current code...
'Populate Connection Object
Dim oCnn As New SqlConnection(strConnection)
'Define our sql query
Dim sSQL As String = "INSERT INTO [" & foreignTable & "] (data_text) VALUES (#data_text) ; "
'Populate Command Object
Dim oCmd As New SqlCommand(sSQL, oCnn)
'Add up the parameter, associated it with its value
oCmd.Parameters.AddWithValue("#data_text", data_text)
'Opening Connection for our DB operation
oCnn.Open()
Try
Dim results As Integer = oCmd.ExecuteScalar
Catch ex As Exception
LabelImport.Text &= "<font color=red>ROOT Import ERROR: " & ex.ToString & ", From Database: " & dbName & ", Text String: " & data_text & "</font><br />"
Throw
End Try
oCnn.Close()
oCmd.Parameters.Clear()
Thanks for any help.

Yeah, that's not right.
It should look like this:
Dim sSQL As String = "INSERT INTO [" & foreignTable & "] (data_text) VALUES (#data_text);"
and for the parameter:
oCmd.Parameters.AddWithValue("#data_text", data_text)
Note: I don't "think" you can pass the table name as a parameter. You would have to have the table name in the string. See Parametise table name in .Net/SQL?
Also, change this:
Dim results As Integer = oCmd.ExecuteScalar
to
Dim results as Integer = oCmd.ExecuteNonQuery()

You can use table name only when creating query (I mean concatenating it from parts: "INSERT INTO " + foreignTable + " (data_text) VALUES..., AFAIK), not as query parameter. Check SqlParameterCollection.AddWithValue on MSDN for more information about SqlCommand parameters, there is very good example as well.
'Populate Connection Object
Dim oCnn As New SqlConnection(strConnection)
'Define our sql query
Dim sSQL As String = "INSERT INTO " & foreignTable & " (data_text) VALUES (#data_text);"
'Populate Command Object
Dim oCmd As New SqlCommand(sSQL, oCnn)
'Add up the parameter, associated it with its value
oCmd.Parameters.AddWithValue("#data_text", data_text)
'Opening Connection for our DB operation
oCnn.Open()
Edit:
+ changed to & because of C# as "native language".

Related

"Operation must be an updateable query" VB.Net OleDB for Excel

Ive been trying to find a solution for this problem without any success:
I'm using VB.NET and I need to read and update records from an Excel file. I use the OleDB API for that. It works fine for all the reading, but impossible to write to the file (Update or Insert queries)
Here is what I have:
My connection string:
Public connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\...\Resources\attempt.xls;Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'"
Select query that works fine:
Dim checkQuery = "SELECT * FROM [Sheet1$] WHERE [TravellerPN] = #T"
Try
Using connection As New OleDb.OleDbConnection(Form.connString)
Dim checkCommand As New OleDbCommand(checkQuery, connection)
checkCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
connection.Open()
Dim reader As OleDbDataReader = checkCommand.ExecuteReader()
Dim path As String = ""
While reader.Read()
path = reader("Datapath").ToString
End While
reader.Close()
MsgBox(PN & " " & DP & " " & path,,)
If a record for the part number entered doesnt exist, and nothing is returned, insert a new line
If path = "" Then
Dim addQuery = "INSERT INTO [Sheet1$] ([TravellerPN],[Datapath]) VALUES (#T, #D)"
Dim addCommand As New OleDbCommand(addQuery, connection)
addCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
addCommand.Parameters.Add("#D", OleDbType.VarChar).Value = DP
Dim rows As Integer = addCommand.ExecuteNonQuery()
And this was where it returns the error.
MsgBox(rows & " row added!",, "") 'Never diplayed
And other query that doesn't work either:
Else 'If does exist, confirm replacement'
Dim replaceResponse = MsgBox("A path already exists for " & PN & "." & vbNewLine & "Do you want to replace " & path & " with " & DP & "?", MsgBoxStyle.YesNo, "Overwrite previous datapath?")
Dim replaceQuery = "UPDATE [Sheet1$] SET [Datapath] = #D WHERE [TravellerPN]=#T"
Dim replaceCommand As New OleDbCommand(replaceQuery, connection)
replaceCommand.Parameters.Add("#D", OleDbType.VarChar).Value = DP
replaceCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
Dim rows As Integer = replaceCommand.ExecuteNonQuery()
MsgBox(rows & " row updated!",, "")
End If
connection.Close()
End Using
I've tried to fix the issue: it could be caused by permissions, so I authorized even guests accounts to modify my folder.
If it were a ReadOnly mode in the connection: I tried adding Mode=ReadWrite but my connection String didn't work after that. (That option seems only available for ADO connections?)
I tried running the app as administrator
And finally, I'm posting this here hoping to get some help.
Sorry or the long post, I was trying to give all the elements that could potentially be a problem.
Thanks.

SQL Result to Global Variable

Within my MDIParent Me_Load I have an SQL query that returns user information based upon Windows ID. This works well, however I'd really like to move this logic out into perhaps a module and assign each value in the db to a global variable to be used elsewhere. I'd like to be able to access the contact_id in any child form of the parent MDI. I'm used to PHP where I'd just assign it to a session variable that I could reference anywhere.
This is my current SQL Code
Dim sql_query As String
Dim errorMessages As New StringBuilder()
Dim cnn = ConfigurationManager.ConnectionStrings("sql_connection_string").ConnectionString
Dim adapter As SqlDataAdapter
Dim ds As New DataTable()
Dim User_ID As String
Dim User_First_Name As String
Dim User_Last_Name As String
Dim User_Contact_CD As String
Dim User_Login As String
sql_query = "SELECT Contact_ID, First_Name_CH, Last_Name_CH, Contact_CD, Login_VC FROM [Worktool].[dbo].[vwEmployees_T] WHERE Login_VC = '" & username & "'"
Using connection As New SqlConnection(cnn)
Try
If connection.State = ConnectionState.Closed Then connection.Open()
adapter = New SqlDataAdapter(sql_query, connection)
adapter.Fill(ds)
User_ID = ds.Rows(0)("Contact_ID").ToString()
User_First_Name = ds.Rows(0)("First_Name_CH").ToString()
User_Last_Name = ds.Rows(0)("Last_Name_CH").ToString()
User_Contact_CD = ds.Rows(0)("Contact_CD").ToString()
User_Login = ds.Rows(0)("Login_VC").ToString()
connection.Close()
Catch ex As SqlException
MsgBox("Sorry, there was an issue with the connection. Please try again ! ")
Dim i As Integer
For i = 0 To ex.Errors.Count - 1
errorMessages.Append("Index #" & i.ToString() & ControlChars.NewLine _
& "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
& "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
& "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
& "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
Next i
MsgBox(errorMessages.ToString())
End Try
End Using
'Assign messages
main_window_welcome.Text = "Welcome back, " & Replace(User_First_Name, " ", "") & " " & Replace(User_Last_Name, " ", "")
variable username is
Public username = Environ$("Username")
You've declared the 4 variables in the class and they are private to that class. At this point your code works. Hilight those 4 variable declarations and Cut them. Your code shows errors because you just removed the declarations.
Add a module to your solution (name it what you want)
paste the declarations into the module body.
change the Dim to Public.
Your errors disappear.
Your variables are now public and available throughout your solution.

Sql query to update new values to column Visual Basic

This is my code:
Dim job As String = TextBoxJobNum.Text
Dim idws As Integer
sqlQuery = "UDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Dim sqlCmd1 As New SqlCommand(sqlQuery, sqlConn)
If sqlConn.State = ConnectionState.Closed Then sqlConn.Open()
For Each row As DataGridViewRow In DataGridViewEquip.Rows
idws = CInt(row.Cells(0).Value)
sqlCmd1.ExecuteNonQuery()
Next
If sqlConn.State = ConnectionState.Open Then sqlConn.Close()
I get the error "Syntax error near '=' " I have searched everywhere but cant seem to find the
correct Syntax for this line. Any help would be greatly appreciated.
Looks to me like you are just missing a "P" in the word "UPDATE"
sqlQuery = "UPDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Also I would recommend not setting parameters using string concatenation, but instead use parameters on a SqlCommand object. The reason for this is reducing potential problems such as additional escaping (if the "job" variable contains a "'" for example) or SQL injection.

Insert Multiple Records into Access DB

What is the most efficient way to insert multiple records into an Access DB with VB.net?
I have a list of objects with multiple properties which are the values for an INSERT query and I want to know can I insert them all together instead of looping through the list of objects, building the query string and executing the queries one by one which is very slow.
Rough example of what I have:
For Each Val In ValueList
ValueString = Val.X.ToString & ", "
ValueString += Val.Y.ToString & ", "
ValueString += Val.Z.ToString
SQLValueList.Add(ValueString)
Next
Dim cmd As OleDb.OleDbCommand
Dim strConnection As String
Dim strSql As String = Nothing
strConnection = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\db.accdb;" & _
"User ID=Admin;Password=;"
For Each ValueString As String In SQLValueList
strSql = "INSERT INTO Results (FldX, FldY, FldZ)" &
"VALUES ( " & ValueString & ");"
cmd = New OleDb.OleDbCommand(strSql)
cmd.Connection = New OleDb.OleDbConnection(strConnection)
cmd.Connection.Open()
cmd.ExecuteNonQuery()
Next
I'm assuming there is a much better and more efficient way of doing this but I haven't been able to find it!
Yes a parameterized query
Imports System.Data.OleDb
.......
Dim strConnection As String
Dim strSql As String = Nothing
strConnection = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\db.accdb;" & _
"User ID=Admin;Password=;"
strSql = "INSERT INTO Results (FldX, FldY, FldZ) VALUES ( ?, ?, ?)"
using cn = new OleDbConnection(strConnection)
using cmd = new OleDbCommand(strSql, cn)
cn.Open()
' HERE all the parameters are added with a string dummy value. '
' This should be changed if one of the underlying field is of different type '
' For example, if FldX is of type integer your need to write '
' cmd.Parameters.AddWithValue("#p1", 0) and then in the loop code '
' '
' cmd.Parameters(0).Value = val.X or '
' cmd.Parameters(0).Value = Convert.ToInt32(val.X) if val.X is not an integer but convertible to... '
cmd.Parameters.AddWithValue("#p1", "")
cmd.Parameters.AddWithValue("#p2", "")
cmd.Parameters.AddWithValue("#p3", "")
For Each val In ValueList
cmd.Parameters(0).Value = val.X.ToString()
cmd.Parameters(1).Value = val.Y.ToString()
cmd.Parameters(2).Value = val.Z.ToString()
cmd.ExecuteNonQuery()
Next
End Using
End Using
This is just an example because it is not clear what kind of data is stored in your ValueList (strings, integers, doubles dates?), but I hope that the idea is clear. Create a command object with 3 parameters (one for each field to insert), add every parameter to the command collection with dummy values (in the example, every parameter contains a string value but you need to add the correct datatype for the underlying field type). At this point just loop one time on your values and execute the query.
Please, stay away to string concatenation to build an sql command, expecially when the string values to concatenate are typed by your user. You risk an Sql Injection attack

Selecting table depends on textbox value

I just created a table programmatically. I named it as my Textbox value.
Example:
Create table " & Textbox1.text & " + ......
I want to set my table name according to my Textbox value.
Select TaskNumber,Name,Age From '" & Textbox1.text & "' "
The best pratice would be to put your textbox value in a variable:
Dim myTableName As String
myTableName = TexBox1.text
// SQL Connection
Dim conStr As String = "Server=MyServer;Database=Mydatabase;Trusted_Connection = yes"
Dim objCon As New SqlConnection(conStr)
Dim obj As SqlCommand
Dim strSQL as String
obj = objConn.CreateCommand()
// *************** Select statement *********
strSQL = "SELECT TaskNumber, Name, Age FROM " & myTableName
// **************** Create statement *********
strSQL = "CREATE TABLE " & myTableName & "(" & _
"Id int NOT NULL PRIMARY KEY IDENTITY, " & _
"ColumnTest VARCHAR(30)) "
// Execute the command
obj.CommandText = strSQL
obj.ExecuteNonQuery()
Try this:
Dim query AS String = "Select TaskNumber,Name,Age From " & Textbox1.Text.Trim().Replace("'","")
.Replace("'","") will prevent SQL-Injection attack due to the presence of single quotes in the TextBox text.
I will suggest you using RegularExpressionValidator on your TextBox to limit the allowed characters.