Backslashes disapearing after my vb.net query to Mysql - mysql

I'm having some problems, when I do my query from my vb.net program to my mysql DB the data is sent, but its missing some things, let me explain.
My query is pretty simple I'm sending a file path to my DB so that after I can have a php website get the data and make a link with the data from my DB, but when I send my data the results look like this...
\server_pathappsInst_pcLicences_ProceduresDivers estCheck_list.doc
which should look like
\\server_path\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc
I don't know if its my code that's not good or my configurations on my mysql server please help...
Here's my code
'Construct the sql command string
cmdString = "INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES('" & filenameOnly_no_space_no_accent & "', '" & str_Lien_Nom_Procedure & "', '" & str_commentaires_Procedure & "')"
' Create a mysql command
Dim cmd As New MySql.Data.MySqlClient.MySqlCommand(cmdString, conn)
Try
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Catch ex As MySqlException
MsgBox("Error uppdating invoice: " & ex.Message)
Finally
conn.Dispose()
End Try
Sorry I got a call and could continue my comment so here's the rest :X
Well I guess that would work, but my program never uses the same path since in uploading a file on a server, so this time the document I wanted to upload was this path
\\Fsque01.sguc.ad\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc
but next time its going to be something else so I can't hard code the paths, I was looking more of a SQL query which that I might not know, since I already thought about searching my string and if it finds a backslash it adds another one, but I feel its not a good way to script the whole thing...
Anyway thanks a lot for your help

When you construct the insert SQL it doesn't have the backslashes escaped. For example:
INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES('\\server_path\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc
The backslashes need to be escaped like:
INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES('\\\\server_path\\apps\\Inst_pc\\Licences_Procedures\\Divers\\test\\Check_list.doc
You can do this with something like (not sure about VB.NET):
filenameOnly_no_space_no_accent = filenameOnly_no_space_no_accent.Replace("\\", "\\\\")
You should also look into parameterised queries, which may protect you from some SQL injection attacks and are a bit easier to write and maintain compared to stitched-together SQL (this isn't tested and I'm not familiar with MySQL parameterised queries so YMMV):
cmdString = "INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES(?nom, ?lien_nom, ?commentaires)"
Dim cmd As New MySql.Data.MySqlClient.MySqlCommand(cmdString, conn)
cmd.Parameters.Add("?nom", filenameOnly_no_space_no_accent.Replace("\\", "\\\\"))
cmd.Parameters.Add("?lien_nom", str_Lien_Nom_Procedure)
cmd.Parameters.Add("?commentaires", str_commentaires_Procedure)
This is based on something I found at this end of this tutorial.

Use double backslashes not single backslash

cmdString = "INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES(?nom,?Lien_Nom,?Commentaires)"
' Create a mysql command
Dim cmd As New MySqlCommand(cmdString, conn)
cmd.Parameters.AddWithValue("?nom", filenameOnly_no_space_no_accent)
cmd.Parameters.AddWithValue("?Lien_Nom", str_Lien_Nom_Procedure)
cmd.Parameters.AddWithValue("?Commentaires", str_commentaires_Procedure)
Try
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Catch ex As MySqlException
MsgBox("Error uppdating invoice: " & ex.Message)
Finally
conn.Dispose()
End Try

Related

Connection Error using mysql in Visual Basic

I'm trying to setup connection to a database within my program, and I'm running into a problem when adding data to the Database. I know I've done something wrong but I can't for the life of me figure it out!
Basically the program throws an error at the ExecuteNonQuery() line, saying the connection is not open. But I've opened the connection just a couple of lines above? It might be because I'm trying to import the connection from a seperate form?
The Error is : An unhandled exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll
Additional information: Connection must be valid and open.
I know some parts are commeneted out, thats just what I do whem I'm troubleshooting.
Imports MySql.Data.MySqlClient
Public Class frmCompanyAdd
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
'Try
frmMain.conn.Open()
' Catch ex As Exception
'End Try
Dim cmd As New MySqlCommand(String.Format("INSERT INTO `Company` (`companyname` , `location` , `contactphone` , `numberpc`) VALUES (" & txtcompanyname.Text & "," & txtPst.Text & " , " & txtPhone.Text & "," & txtPcNo.Text & ")"))
cmd.ExecuteNonQuery()
'frmMain.conn.Close()
End Sub
It looks like you never set the connection on the cmd command after you construct it. You either need to provide the connection in the constructor or set it afterwards.
As usual, I must also point out that your INSERT statement is open to a possible malicious SQL injection attack. You should use a parameterized query instead of concatenating values together to form your query.
I can't get the library installed, but it's probably just a constructor overload, e.g. Dim cmd As New MySqlCommand(yourProperlyParameterizedQuery, frmMain.conn)

SQL Updates/Inserts with data with double quotes

I have a database that collects client information using assessments and other tools. Often in the assessments there are double quotes in the data when - as may be expected - a direct quote is captured. When I run sql updates (Access front end using VBA to SQL Server 2008 R2 backend) it blows up on double quotes in the data. In the interim I've asked staff to use single quotes when they enter data, but that is an unsustainable solution as they forget and the program crashes when it hits the double quotes. The datatype is nvarchar(max).
The current VBA string looks like this:
strInsertSQL = "INSERT INTO tblIRPDetail(IRPID, SectionID, Challenge, Goal, Objective, Intervention, IntDate) VALUES(" & intNewID & ", " & intSection & ", """ & strChallenge & """, """ & strGoal & """, """ & strObjective & """, """ & strIntervention & """, """ & strIntDate & """);"
Essentially any of the strVariables could have single or double quotes in any combination. It works for single quotes but not doubles. Surely this is a fairly common issue, I'm hoping someone has a simple solution!
Thanks in advance!
An Access SQL statement can use either single or double quotes for text values. So you could use single quotes in your INSERT statement, but then you would run into a similar problem when the text to insert includes single quotes and which you could then resolve by doubling up the single quotes within the insert text:
Replace(strChallenge, "'", "''")
That doesn't seem like much of an improvement. OTOH, since you're using VBA to insert a row to your table, you don't need to use an INSERT query.
Open your table as a DAO.Recordset, add a new row, then assign your variable values to the corresponding fields.
Public Sub NPO_AddRow()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("tblIRPDetail", dbOpenTable, dbAppendOnly)
With rs
.AddNew
!IRPID = intNewID
!SectionID = intSection
!Challenge = strChallenge
!Goal = strGoal
!Objective = strObjective
!Intervention = strIntervention
!IntDate = strIntDate
.Update
.Close
End With
Set rs = Nothing
Set db = Nothing
End Sub
Note that, unlike a parameter query, this approach will allow you to add text strings longer than 255 characters.
Parameterize you query and add the values as parameters instead.
This might help:
parameterized query in ms access 2003 using vba
give me a minute and ill copy over the methods i used to get this performed.
In the mean time why not do a Replace(val, """, "'")? That way any instance of a " in the string will be replaced with a single quote '?

Getting "final" prepared statement from MySqlCommand

I have the following MySqlCommand:
Dim cmd As New MySqlCommand
cmd.CommandText = "REPLACE INTO `customer` VALUES( ?customerID, ?firstName, ?lastName)"
With cmd.Parameters
.AddWithValue("?customerID", m_CustomerID)
.AddWithValue("?firstName", m_FirstName)
.AddWithValue("?lastName", m_LastName)
End With
I have a class that handles execution of MySqlCommands and I'd like to have it log every query to a file. I can retrieve the query/command being executed with:
cmd.CommandText
but that just returns the original CommandText with the parameters (?customerID, ?firstName, etc.) and not the actual substituted values added by the AddWithValue functions. How can I find out the actual "final" query that was executed?
I did the following:
dim tmpstring as string = MySqlCommand.CommandText
For each p as MySqlParameter in MySqlCommand.parameters
tmpstring = tmpstring.replace(p.ParameterName, p.Value)
Next
This seems to output everything you need
I havn't seen a method for this.
And in any case, prepared statements are sent to the server with the ?customerID,?firstname parameters, and then the actual parameters are sent seperately - the mysql driver doesn't build up a final sql query like you'd do if you didn't use prepared statements.
The parameterised method you're using should be okay for preventing SQL injection.
.AddWithValue("?customerID", m_CustomerID)
If m_CustomerID contains the text
Haha I'm stealing your data; drop table whatever;
Then it won't end up being executed on the server as such. The AddWithValue sorts that out for you.
As for the actual executed query, you should be able to get that from the query-log, if it's enabled.
You would have to build it yourself.
Parameters are not just plopped into a string and then run as a SQL statement. The RDBMS will actually prepare the SQL and then use the parameter values as needed. Therefore, there's not a single SQL statement going to the server. To see what the SQL would be, you would have to do:
Console.WriteLine("REPLACE INTO `customer` VALUES('" & m_CustomerID & _
"', '" & m_FirstName & "', '" & m_LastName & "')")
I have the same need.
From what I've read, the query text isn't combined with the param values in the client - they are sent to the server for that.
To inspect what query was actually being sent to the server, I used mysqld logging. For my version of MySQL, I added this entry to the my.cnf:
log=queries.txt
Then, I was able to see clearly the effect of combining command text with parameters: in my case, after restarting the mysqld, I ran my unit tests and then opened the queries.txt file.
HTH!
If you want to manage logging yourself from the .NET application, your best bet is to continue using the MySqlCommand class with parameters to avoid SQL injection; however, when you log the CommandText, loop through the Parameters collection and log each one by name/type/value.

Visual Basic 2008 - NullReferenceException ERROR?

I'm using Visual Basic 2008 here, and I'm debugging my code that connects to my SQL Database and writes something in it. It was working fine and all until I came to an error like this. NullReferenceException was unhandled. What's going on? Here is the code I'm working with:
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "server=...; user id=...; password=...; database=..."
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("Error connecting to database")
End Try
Dim myAdapter As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM user WHERE username = '" + TextBox2.Text + "'"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
It highlights it right around conn.open(), and gives me that error. It was working fine earlier until I moved my sql database to my mac. (windows -> mac) Is there a difference? I backed up my stuff from my windows vista computer and restored it on my mac. I don't think there is a difference, but I'm just putting that out there. Why does this error come up?
Thanks,
Kevin
I would suggest reviewing your connection string. I used your code and connected to our local MYSQL db no errors.
I can't really say what the problem is off the top of my head.
But the way to find out would be to put a breakpoint on the conn=New MySqlConnection and look at the variables you have as you step through.
If the problem is happening on the conn.Open line then it would probably be because conn is null (nothing). But if that is the case then conn.ConnectionString should have thrown an exception.
The other step is to look at the stack trace of the exception and see where, exactly, it is being thrown from. It could, for example, be an error somewhere inside the mysql connector.
Sorry I can't really give you a definate answer, but I thought some general comments might help you to the solution or find some more detail.
Whivh version of MySql are you using? Have you looked at the details of this bug...
http://bugs.mysql.com/bug.php?id=26393
... which is related to idle time.
If you had the full stack trace associated with the exception then it might shed some light on the problem.

vbscript to export an access query to a tab delimited file not working

I have this code:
db = "C:\Dokumente und Einstellungen\hom\Anwendungsdaten\BayWotch4\Neuer Ordner\baywotch.db5"
TextExportFile = "C:\Dokumente und Einstellungen\hom\Anwendungsdaten\BayWotch4\Neuer Ordner\Exp.txt"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source =" & db
strSQL = "SELECT * FROM tblAuction1"
rs.Open strSQL, cn, 3, 3
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile(TextExportFile, True)
a = rs.GetString
f.WriteLine a
f.Close
Which is meant to connect to an access database and produce a tab delimited text file. tblAuction1 is a query in the database, and definitly exists and is not misspelt in any way, but I get an error that it cannot be found or does not exist. When I change it to tblAuction which is the name of the table, I get an error stating f.WriteLine a has been called incorrectly.
edit: I now only get a problem with f.writeline a, saying an incorrect argument has been supplied. I no longer have a problem with tblAuction1
edit: the sql code used for my query:
SELECT tblAuction.article_no, tblAuction.article_name, tblAuction.subtitle, tblAuction.current_bid, tblAuction.start_price, tblAuction.bid_count, tblAuction.quant_total, tblAuction.quant_sold, tblAuction.start, tblAuction.ends, tblAuction.origin_end, tblUser.user_name, tblAuction.best_bidder_id, tblAuction.finished, tblAuction.watch, tblAuction.buyitnow_price, tblAuction.pic_url, tblAuction.private_auction, tblAuction.auction_type, tblAuction.insert_date, tblAuction.update_date, tblAuction.cat_1_id, tblAuction.cat_2_id, tblAuction.article_desc, tblAuction.countrycode, tblAuction.location, tblAuction.condition, tblAuction.revised, tblAuction.paypal_accept, tblAuction.pre_terminated, tblAuction.shipping_to, tblAuction.fee_insertion, tblAuction.fee_final, tblAuction.fee_listing, tblAuction.pic_xxl, tblAuction.pic_diashow, tblAuction.pic_count, tblAuction.item_site_id
FROM tblUser INNER JOIN tblAuction ON tblUser.id = tblAuction.seller_id;
I have tried to reproduce this on several databases and machines, I can't get your code to fail.
Leaves :
a corrupt database, could you please run repair and try again ?
Fields in your database that are throwing of the query, I have tried several possibilities but can't find anything that brakes your code. To exclude other things you could try to create a new table and see if your code works on that table.
something wrong with your dll's , could you try it on another machine.
Answer (to see how we came to the answer see the comments)
There are unicode characters in your database that writeline does not accept because you created the textfile as ASCI.The characters in this case specifically where ♥♥♥
To make it work:
Set f = fs.CreateTextFile(TextExportFile, True, True)
P.S.
This question was answered earlier using the transfertext macro here
As Remou points out this looks like a cleaner solution. To make it work with non-default delimiters is a bit of a pain. First start exporting the query you like to export by right clicking and choose export. In the following dialogs specify the specifications and save these. When creating the macro select the specifications you just saved.
I think there is something wrong with the spaces in your connection string
Try this:
cn.Provider = "Microsoft.Jet.OLEDB.4.0"
cn.ConnectionString = db
cn.Open
HTH
Update:
Maybe there is a problem with the access rights to the database?
Or the mdb is already opened exclusively by another user (You with your access in design mode)?
Try this
cn.Open _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Persist Security Info=False;" & _
"Data Source=" & db