Using the Replace() function in a parameterized query - sql

I have the below mentioned code trying to perform an update/replace function on each row in the database where it finds the "Search" Pattern being stored in the parameter. However, when I run the query in the VB.NET program, the program is skipping over the row that it is supposed to be hitting.
For example, say the intQuestionID variable is set to 4. And within the QuestionStacks table is a value ;4;0;14;24;34;. The SQL should be replacing the first ;4; with ;0; but it is not. In fact, nothing is being changed. Even if the value is a sole ;4;.
Dim sqlClearQuestion As New OleDb.OleDbCommand("UPDATE QuestionStacks SET QuestionData = REPLACE([QuestionData], "";#0;"", "";0;"") ", DBConnection)
sqlClearQuestion.Parameters.AddWithValue("#0", intQuestionID)
sqlClearQuestion.ExecuteNonQuery()
I've checked this query by running the SQL in the Query Builder in Access 2016 and it works fine as intended. However, attempting to use it in this VB.NET function, it is not yielding the desired result. What change is needed for this?
N.B. I know that .AddWithValue on Access SQL isn't needed, and is actually changed to something else (Read: https://stackoverflow.com/a/6794245/692250). But with only one parameter, there shouldn't be any problem with this.

One should always be suspicious when they see delimiters or any other decoration surrounding a parameter placeholder. Parameter placeholders should appear alone, with any required special characters in the parameter value. For example, a very common mistake is to try and use
' no good
cmd.CommandText = "SELECT * FROM Students WHERE FirstName LIKE '?%'"
cmd.Parameters.AddWithValue("?", theName)
when the correct approach is to use
' good
cmd.CommandText = "SELECT * FROM Students WHERE FirstName LIKE ?"
cmd.Parameters.AddWithValue("?", theName & "%")
In your particular case, you'll want to use
cmd.CommandText = "UPDATE QuestionStacks SET QuestionData = REPLACE([QuestionData], ?, "";0;"") "
cmd.Parameters.AddWithValue("?", ";" & intQuestionID & ";")

Related

Read Value from Database in TextBox when Combobox text changes VB.NET

I have a list of Users Names in ComboBox and Some TextBoxes. When ComboBox text changes (i.e I select some username from ComboBox), The TextBoxes are filled with user details from the database.
I have code to achieve this in SQL Database. But these queries are not working with MsAccess database.
MysqlConn = New MySqlConnection
Mysql.ConnectionString = "server=localhost;user=root;password=root;database=database"
Dim READER As MySqlDataReader
Try
MysqlConn.open()
Dim Query As String
Query("select * from database.usernames where name='" & ComboBox1.Text & "'")
Command = New MySqlCommand(Query, MysqlConn)
READER = Command.ExecuteReader
While READER.Read
TextBox1.Text = READER.GetString("name")
End While
End Try
Here is my answer. Please don't get overwhelmed by it. ;)
Broken code
First of all, as I see it, the code you provided cannot work at all, because:
your Query variable is initialized in an invalid (or at least a very exotic) way. You probably want to use something like:
Dim Query As String
Query = "select * from database.usernames where name='" & ComboBox1.Text & "'"
or in a single line:
Dim Query As String = "select * from database.usernames where name='" & ComboBox1.Text & "'"
you try to assign the connection string to the ConnectionString property of a nonexistent Mysql variable. Or the variable exists because it is declared somewhere else, which might be a bug in your code snippet here. But I assume you want to assign the connection string to the MysqlConn.ConnectionString property instead.
you have not declared the MysqlConn and Command variables anywhere. You only just assign to them. (I will simply assume you have declared the variables correctly somewhere else in your code...)
the IDataRecord interface does not provide a GetString(name As String) method overload. So unless you have defined a custom extension method for it, you probably need to use the IDataRecord.GetOrdinal(name As String) method as well, or use the column index instead of the column name.
Anyway, the code you provided uses MySQL. So I assume that MySQL is the "SQL Database" you are using successfully. And that seems to work, as you say? Well... Hmmm... Then I will simply assume your code snippet is completely correct and works perfectly with MySQL... :/
MS Access vs. MySQL
Using MS Access requires other data access classes (probably the ones in namespace System.Data.OleDb) and another connection string. You could take a look at this ADO.NET OleDb example for MS Access in the Microsoft documentation.
You probably even have to update your SQL query, because every database system uses its own SQL dialect. You might want to consult the Office documentation for that. But your query is quite simple, so perhaps all you have to do to make it work with MS Access is:
remove the database name and use only the table name, and
delimit the name identifier (since it is a reserved keyword in MS Access).
I personally delimit all identifiers in my SQL queries, just to avoid unintended conflicts with reserved keywords. So I would personally use something like this:
select * from [usernames] where [name] = '...'
Additional tips
Also, I would like to provide you some additional (unrelated) tips regarding improving your code:
Use Using-statements with variables of an IDisposable type as much as possible. Those types/classes do not implement that interface if there isn't a good reason for it, so I consider it not unimportant to call Dispose when you are done with such disposable objects (or using a Using statement to call Dispose implicitly).
Use SQL parameters (if possible) to avoid SQL injection vulnerabilities. Look at this StackOverflow question and its answer for an example of how to use SQL parameters with MS Access.
Example
You may take a look at the following code snippet. It might not provide a working example out-of-the-box, but you might get some useful/practical ideas from it:
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\\database.mdb;User Id=admin;Password="
Dim query As String = "select * from [usernames] where [name] = #Name"
Using conn As New OleDbConnection(connectionString)
Using command As New OleDbCommand(query)
command.Parameters.Add("#Name", OleDbType.VarChar, 50).Value = ComboBox1.Text
conn.Open()
Using reader As OleDbDataReader = command.ExecuteReader
If reader.Read Then
textbox1.Text = reader.GetString(reader.GetOrdinal("name"))
End If
End Using
End Using
End Using

SQLite Inserts - How to Insert Any Text while Avoiding Syntax Errors using Parameterized Values

I'm curious to know a proper way to insert text strings into a database regardless of what characters are contained within the string. What I'm getting at is if I have a string for example that contains single quotes or any other character that is reserved as a 'special' SQL character.
The issue specifically that I'm dealing with is that I don't have control over the possible 'Text' that is being inserted into my database as they text is generated by my application.
One example of where my application fails to insert properly is when there's an error message that happens to contain single quotes. Single quotes are used by SQL statements insert text of course and so I can't insert text that also contains single quotes (outside of using ascii value char(##) function). The issue I'm dealing with is that I'm setting the output of my application to a string variable to then be inserted into my database so I can log activity whether that be standard output or catching errors.
How do I simply INSERT what's contained in my string variable while avoiding all of the SQL Special characters?
Do I need to manually account for all of the SQL Special characters and replace them in my string prior to insert? This sounds like a hit or miss and I'm hoping that there's something already built to accommodate this situation.
Sample Pseudo Code to get the point across:
Let's say an error occurred within the app and it needs to be logged. The error string could be:
Error String: "Error in function calculateStats() parameter 'pBoolStatCheck' is Null"
Now I assign to my string variable within my app and build up the SQL Insert string.
var insertString = "Error in function calculateStats() parameter 'pBoolStatCheck' is Null"
INSERT INTO outputLog(outputLogText)
VALUES ('insertString'); --This will Fail
--Fails due to the variable 'insertString' containing single quotes.
INSERT INTO outputLog(outputLogText)
VALUES ('Error in function calculateStats() parameter 'pBoolStatCheck' is Null');
In closing - since I have no control over the text that could be created by my application how do I account for all of the possible characters that could break my insert?
The code my current application encountering this issue is written in Visual Basic. The database I'm working with is SQLite.
The final solution based on answers received by this post:
Public Sub saveOutputLog(pTextOutput, pTextColor, pNumNewLines, plogType, pMethodSub)
Dim strTableName As String = "outputLog"
Dim sqlInsert As String = "INSERT INTO " & strTableName & "(" &
"outputLog, logColor, numNewLines, logType, method" &
") VALUES (#outputLog, #logColor, #numNewLines, #logType, #method);"
Try
'Open the Database
outputLogDBConn.Open()
'Create/Use a command object via the connection object to insert data into the outputLog table
Using cmd = outputLogDBConn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = sqlInsert
cmd.Parameters.AddWithValue("#outputLog", pTextOutput)
cmd.Parameters.AddWithValue("#logColor", pTextColor)
cmd.Parameters.AddWithValue("#numNewLines", pNumNewLines)
cmd.Parameters.AddWithValue("#logType", plogType)
cmd.Parameters.AddWithValue("#method", pMethodSub)
'Execute the command using above Insert and added Parameters.
cmd.ExecuteNonQuery()
End Using 'Using outputLogDBComm
outputLogDBConn.Close()
Catch ex As Exception
outputLogDBConn.Close()
End Try
End Sub
This problem is very similar to the problem of preventing SQL Injection vulnerabilities in your code. Queries are very easy to break, and while yours breaks in a way that is harmless and annoying, these can be taken to levels where certain inputs can completely destroy your database!
One of the best ways to approach this is by using parameterized queries. This approach is pretty simple; you write the query first with 'placeholders' for the parameters you will send. Once you are ready in your program you can then 'bind' those parameters to the placeholders.
It would look something like the following:
Dim command = New SqlCommand("INSERT INTO outputLog(outputLogText) VALUES (#stringToInsert)", connection);
.
.
.
code
.
.
.
command.Parameters.AddWithValue("#stringToInsert", errorMessage)
.
.
.
execute query
In the above you see that #stringToInsert is the placeholder which is only bound at a later time. It doesn't matter what the variable errorMessage contains, since it will not cause the query to function in a way where the input causes it to potentially break.
There are a lot of resources on this:
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.prepare?view=netframework-4.7.2
Database objects like connections not only need to be closed but also disposed. A Using block will ensure this will happen even if there is an error.
The .Add is better than .AddWithValue for a number of reasons. See https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ and http://www.dbdelta.com/addwithvalue-is-evil/
The parameters of .Add are the name of the parameter, the datatype in the database and optionally the size of the field. You will need to check the database for the last 2.
Open the connection at the last minute befor the execute.
If you are using OleDb with Access, you need to make sure the parameters are added in the same order as they appear in the sql statement.
Using cn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("INSERT INTO outputLog(outputLogText) VALUES (#outputLogText);", cn)
cmd.Parameters.Add("#outputLogText", SqlDbType.VarChar, 100).Value = TextBox1.Text
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using

Having an issue inserting data into Postgresql using Npgsql and VB.net

Can someone please look at my code and possibly point me to why it is not allowing me to insert data into my Postgres database? I'm creating a Comic Book database for my collection.
Everytime I click my submit button to submit the data entered, the debugger throws an exception:
'An unhandled exception of type 'Npgsql.PostgresException' occurred in Npgsql.dll'
Which happens on the execution of myCommand.ExecuteNonQuery() function.
I've spent my day trying to figure this out, I am a complete noob at this. Any guidance would be awesome!
Dim myConnection As NpgsqlConnection = New NpgsqlConnection()
Dim myCommand As NpgsqlCommand
Dim mySQLString As String
myConnection.ConnectionString = "Server=localhost;Port=5432;Database=ComicsDatabase;User Id=postgres;Password=xxxxxxxx;"
mySQLString = "INSERT INTO Comics (IssueName,IssueNumber,PublicationDate,Publisher,IsVariant) VALUES (" & comicName & "," & issueNumber & "," & publicationDate & "," & publisher & "," & isVariant & ");"
myCommand = New NpgsqlCommand(mySQLString, myConnection)
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
When you concatenate strings as above to form your sql command it is very easy to fall in common errors. In your code, for example, a string value should be enclosed between single quotes.
So, supposing that IssueName is a string type field, you should express the value in this way
.... VALUES ('" & comicName & "'," & ....
But this is a remedy worse than the illness. First you will have another problem if your comicName variable contains a single quote, second the concatenation of strings is the main way that leads to Sql Injection (a very dangerous code vulnerability)
The only correct way to pass a value to a database engine (...any database engine of this world) is through a parameterized query
You write the query putting parameter placeholders instead of directly the values
(No string concatenation, no weird & and single quotes....)
mySQLString = "INSERT INTO Comics
(IssueName,IssueNumber,PublicationDate,Publisher,IsVariant)
VALUES (:comicName,:issueNumber,:publicationDate,:publisher,:isVariant);"
And then you pass the value using a parameter added to the command parameters collection
myCommand = New NpgsqlCommand(mySQLString, myConnection)
myCommand.Parameters.Add(":comicName", NpgsqlDbType.Varchar).Value = comicName
Of course you need to add all the other parameters required by the placeholders, the important thing to keep in mind is to use the correct NpgsqlDbType for the specific column that you are trying to update.

MS Access VBA issue

I'm making a report in MS Access - what I'm trying to do here is basically APPEND a query to a table that I've already created - I select the first value, change it and update the table. The issue that I'm coming across is - this report will be used by a VB6 application. So the user won't be seeing Access at all.
The thing with my append query is that it needs a USER ID to run (4 digit number). Normally when I run a report in Access I pass the parameters to a form in Access - and I use them to run queries. However, in this case, I need the user to enter a value when appending the query, additionally, when appending a query in VBA it first says "You are about to append a query, are you sure" (or something along those lines), so is there a way to automate that as well, so when I append it nothing happens?
Here is my code for appending and selecting date from the tempTable:
CurrentDb.Execute "DELETE from [tempCompanyMgmt-NOW];"
DoCmd.OpenQuery "qryCompanyMgmt-SUE" - i made this append!
Set rs1 = CurrentDb.OpenRecordset("Select * from [tempCompanyMgmt-NOW]", , dbOpenDynamic)
So as long as I press OK, YES when I get notified of the APPEND process and enter the parameter for USER ID - everything works fine.
Looks like a typo in your markdown, should the 2nd line be:
DoCmd.OpenQuery "qryCompanyMgmt-SUE - i made this append!"
You'll need to remove the reference to the form inside the qryCompanyMgmt-SUE - i made this append! query, and swap it for a parameter name. You can use the Access interface to explicitly add a parameters clause to the query, and then using ADO (or DAO) from VB6, set a parameter value before you open/execute the query.
The "You are about to append a query, are you sure" message is an Access feature (and it can be disabled), so if you want the VB6 application to provide such a warning, then you'll need to create it yourself with a MsgBox.
One option would by putting your append query into the code and filling in the parameter that way.
I don't know your exact scenario, but something like:
If not isValidUserID(me.UserID) Then
msgbox "Please enter a a valid user id"
exit sub
End If
Dim strSQL As String
strSQL = "DELETE * from [tempCompanyMgmt-NOW];"
CurrentDb.Execute strSQL, dbFailOnError
strSQL = "INSERT INTO tempCompanyMgmt-NOW ( FieldName1, FieldName2, FieldName3 ) " & _
"SELECT FieldName1, FieldName2, FieldName3 FROM tempCompanyMgmt WHERE UseriD=" & Me.UserID
CurrentDb.Execute strSQL, dbFailOnError
To validate the user id you could do something like:
If (Len(me.UserID) = 4 And IsNumeric(me.UserID)) Then
or
Public Function isValidUserID(varUserID As Variant) As Boolean
Dim blnRet As Boolean
If Len(varUserID) = 4 And IsNumeric(varUserID) Then
blnRet = True
End If
isValidUserID = blnRet
End Function
To get rid of the MsgBox telling me I'm about to append a query i included this in my module before I open my append query..
DoCmd.SetWarnings False
And I realized once I have the value passed to the form (userID), that value gets passed on as a parameter when my query gets appended. So it's all set. Thanks for all help!

VB Access DB Update statement

I am new to this forum, please could you help me get this code to work, when i execute it, it simply does nothing and does not update the DB. If i remove the square brackets it gives an error: "SYNTAX ERROR in UPDATE statement"
Any help appreciated!
Dim connection As OleDbConnection
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserDB.accdb;Jet OLEDB:Database;")
connection.Open()
Dim pass As String
pass = txtconfirm.Text
Dim user As String
user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= '" & pass & "' WHERE [Username]= '" & user & "';"
Dim command As New OleDbCommand(query, connection)
command.ExecuteNonQuery()
connection.Close()
Given your actual connection string, the database that will be updated is the one in the directory where your application starts. This means that if you work with a WinForms application this folder is \BIN\DEBUG or x86 variant. If there is not error then you could get the return value of the ExecuteNonQuery call to verify if a record has been updated or not
Dim rowsUpdated = command.ExecuteNonQuery()
MessageBox.Show("Record updated count = " & rowsUpdated)
If this value is not zero then your database has been updated and you are looking for changes in the wrong database. Check the one in the BIN\DEBUG folder.
In any case your code has big problems. If your variables user or pass contain a single quote, then your code will crash again because your string concatenation will form an invalid SQL. As usual the only workaround is to use a parameterized query
Dim pass = txtconfirm.Text
Dim user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= #p1 WHERE [Username]= #p2"
Using connection = New OleDbConnection("...........")
Using command As New OleDbCommand(query, connection)
connection.Open()
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = pass
command.Parameters.Add("#p2", OleDbType.VarWChar).Value = user
command.ExecuteNonQuery()
End Using
End Using
The parameterized approach has many advantages. Your query text is more readable, there is no misunderstanding between your code and the values expected by your database engine. And while not easy to exploit with MS-Access there is no problem with Sql Injection
I think Steve presents a much better approach for you coding this...
Let me just throw out a few more things:
The reason you can't take those brackets out is some of your column names are reserved words; just FYI.
Since you report "it does nothing..." when you execute, it sounds like you have a valid connection and sql syntax, in which case my next step would be to copy the sql command text while in debug mode, change it to a select and run it in your DB. You should get one result when you do. If not, either your criteria or field contents are not what you think they are...
Just change the Update table SET field-value ... to SELECT * FROM table and leave the WHERE clause as is.