My oledb connection string has a " in it so is not recognized - vb.net

Im trying to run an update statement and when i go to data sources to grab the connection string it has a " in it which means when i try to add it to the line;
OleDbConnection(Provider=Microsoft.ACE.OLEDB.12.0;Data Source="C:\Users\Student\Documents\Visual Studio 2010\Projects\MasterDB.accdb")
It wont accept it, I tried to & & it but then i still need double speech marks.
is there some sort of way to force vb.net to ignore the speechmark?
Any help is much appreciated.

Related

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

Using dynamic connection strings to connect to sybase via vb.net

I need you help to get the syntax for assigning the server, port and database name using parameters.
the script works perfectly fine if I pass the variable in the command explicitly.
Dim myConn1 As Odbc.OdbcConnection = New Odbc.OdbcConnection("Driver=Adaptive Server Enterprise;uid=XXX;server=& SRVR &;port=& PRT &;database=& dbname &;pwd=XXX")
Please advise me where am I going wrong.request for Your prompt assistance.
Thanks
Mayur
You're not actually concatenating any strings. How many double quotes are there in this:
"Driver=Adaptive Server Enterprise;uid=XXX;server=& SRVR &;port=& PRT &;database=& dbname &;pwd=XXX"
There are exactly two, which means that that whole thing is one string. If you want to join multiple strings then there have to actually be multiple strings:
"Driver=Adaptive Server Enterprise;uid=XXX;server=" & SRVR & ";port=" & PRT & ";database=" & dbname & ";pwd=XXX"
You can avoid silly issues like this by not using string concatenation in the first place. You could use String.Format or, in VB 2015, string interpolation to make things clearer or you could do what you're supposed to do when building a connection string from parts and use a connection string builder. As you're building an ODBC connection string, you would use the OdbcConnectionStringBuilder class:
Dim builder As New OdbcConnectionStringBuilder("Driver=Adaptive Server Enterprise;uid=XXX;pwd=XXX")
builder("server") = server
builder("port") = port
builder("database") = database
Using connection As New OdbcConnection(builder.ConnectionString)
'...
End Using

Vb.NET rasdial parameters

I am making a program that schedules the redial of a VPN connection using rasdial however I cannot get my script to pass the correct information to the rasdial.exe program.
For example
Process.Start("rasdial.exe", "VPN Connection " & ""USERNAME!" & "PASSWORD")
However when this starts it just says "Remote access error 625"
It turns out that the best solution is to concatenate the variables before storing them in a database or document because the connection only inputs one parameter.

Is it possible to replace " (double quotes) with a white space in a string?

At some point of execusion of my project, the input to the database is in the format:
Buy Requirement of "xxxxxx & xxxxxx" through mycompany.com
It results in an incorrect SQL syntax error. I need to replace " with white space. I searched in google but no helpful suggestions were there.
How to replace " with whitespace?
Dim str As String
str="Buy Requirement of "Telemarketing & ERP Software" through IndiaMART.com"
' TODO: perform replace
' result
str = "Buy Requirement of Telemarketing & ERP Software through IndiaMART.com"
I finally understand what you are asking now...
Here, this is what you want to be using: teststring.Replace(""""c, "")
If you really want to use Linq and extension methods, then use this: New String(teststring.Where(Function(c) Char.IsLetterOrDigit(c) OrElse Char.IsWhiteSpace(c)).ToArray()).
But that's just making things complicated for no reason.

sqlite in vb.net, can't find table even though it exists

I'm using the following code (System.Data.SQLite within VB.net):
Dim SQLconnect As New SQLite.SQLiteConnection()
Dim SQLcommand As SQLiteCommand
SQLconnect.ConnectionString = "Data Source=vault.db;"
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "INSERT INTO entries VALUES ('" & appinput.Text & "','" & userinput.Text & "','" & passinput.Text & "')"
SQLcommand.ExecuteNonQuery()
SQLcommand.Dispose()
SQLconnect.Close()
Me.Hide()
I get an error back that says it can't find the table "entries"
I know the table exists because I can write to it via the command line through sqlite and through Autoit and can see it and edit it in the SQLite browser when I open the database. I don't understand why VB can't see it (I know it sees and opens the database file just fine). Any ideas?
Most likely your problem is with relative paths (directories).
sqlite will create a database file if it does not exist so you will never get a "db file not found message". The first indication of an incorrect path is "table missing".
My personal experience is that although it goes against my programmers instinct is to alway use an absolute (fully qualified) path/file name for an sqlite database.
If you put in the full file location like "/var/myapp/vault.db" you should be OK.
If this is likly to move around store pick up the file name from a properties/config file -- 'config file not found' is much easier to deal with than "table not found".
Argh! There are 3 big issues in that code. Please update it like this to fix two of them:
Using cn As New SQLite.SQLiteConnection("Data Source=vault.db;"), _
cmd As New SQLiteCommand("INSERT INTO entries VALUES (#AppInput, #UserInput, #PassInput)", cn)
cmd.Parameters.AddWithValue("#AppInput", appinput.Text);
cmd.Parameters.AddWithValue("#UserInput", userinput.Text);
cmd.Parameters.AddWithValue("#PassInput", passinput.Text);
cn.Open()
cmd.ExecuteNonQuery()
End Using
This will prevent sql injection by parameterizing your query instead of substituting values directly and prevent db locking issues by making sure your connection is disposed properly, even if an exception is thrown.
The third problem is that you should NEVER store plain-text passwords in your database (or anywhere else for that matter). Go read up on how to hash values in .Net and hash and salt your password before storing or comparing it.
Once you've done that re-test your code to see if you still get the same errors reported as before. We need to make sure this didn't solve the problem or introduce something new. Then we can start addressing the missing table issue, perhaps by checking your connection string.
I had a similar error with SQLite (via .Net) refusing to believe the table existed, even though direct access confirmed it was there. The error could be produced only on one individual machine and not others. Hard coding the path didn't seem to fix the problem. The fix was either to run the program as Administrator or change the DB file to be available to Everyone. Apparently the .Net assembly raises a missing table error when the actual problem is access restrictions.