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)
Related
So, I´ve an application that comunicates with a remote mysql db, so its on hostinger and works properly for more de 2 years, and few days ago its just stop working, and the error happens when I try to open connection, the error its about it ↓
The handshake failed due to an unexpected packet format
but what i dont get is, I´ve tested the same connection on 2 different compannies, and on hostinger its doesnt work, but on another works fine....Im using vb.net and remote mysql on hostinger...
I´d like to know if someone could help me...
the code just to test open the connection is ↓
Dim conn As String = "Server=myserver-here;Port=3306;Database=u8424_test;Uid=u8424_teste;Pwd=Test2021"
Using cn = New MySqlConnection(conn)
Try
cn.Open()
MsgBox("SUCESS")
cn.Close()
MsgBox("CLOSING CONNECTION")
Catch ex As Exception
MsgBox("SOME ERROR..." & vbNewLine & ex.ToString)
End Try
End Using
since then, thanks for everyone!
so in my case, I got the solution, in fact the problem was on hostinger, that changed their configuration and now we´ve to put the param about ssl in the end of the connection string, something like this already works here for me↓
Dim conn As String = "Server=myserver-here;Database=u8424_test;Uid=u8424_teste;Pwd=Test2021;ssl mode=none;"
even if you dont use ssl, you must put something, but you have to pass this param or some of these list ↓
https://dev.mysql.com/doc/dev/connector-net/6.10/html/T_MySql_Data_MySqlClient_MySqlSslMode.htm
I am trying to create a connection string to get to Snowflake data from Access 2010 and above. I can create a database DSN and link to the tables I use, but I need to build DSN-less connection strings for distributed applications. Here's what I have so far, it fails with the message "ODBC connection to xxxx failed". Here's what I have so far:
ODBC;Driver={SnowflakeDSIIDriver}; Server=https://server name; Role=role name;Warehouse=warehouse name;Database=db name;Schema=schema name;UID=snowflake ID; PWD=snowflake password;
I think you are on the right track. I have the same thing and it works.
ODBC;
driver={SnowflakeDSIIDriver};
server=accountname.snowflakecomputing.com;database=dbname;
schema=public;
warehouse=whname;
role=rlname;
Uid=userid;
Pwd=password;
Very odd that the DSN one works and your doesn't.
I can confirm that DNS-free connections work fine in Access 2013. I have not tested on Access 2010, but I have it available if that needs testing.
The first problem I encountered is that the Snowflake ODBC driver reports 32/64-bit in the ODBC section of Control Panel, but it may not have one or the other installed.
In my case, it showed in the DSN sources as 32/64-bit, but I had only the 64-bit version installed. Notice that after installing the 32-bit driver, the Programs and Features (where to go normally for uninstalling apps) shows both the 64 and 32 bit drivers.
After installing the 32-bit driver, it was just a matter of getting the connection string right. You want to copy it from the URL on your Snowflake web UI. Strip off the https:// part, and then keep everything up to and including the snowflakecomputing.com in the url. That's what you'll use for the server.
Edit 2: I missed the part of the question that referenced pass through queries and was describing a procedure I tested recently for DNS-free connection using VBA. I tested the pass-through connection and it worked fine. The only difference is in the ODBC connection string you need to keep the "ODBC;" prefix:
ODBC;Driver{SnowflakeDSIIDriver};server=<your_URL_everything_before_snowflakecomputing.com>.snowflakecomputing.com;uid=greg;pwd=xxxxxx
Edit: One thing I forgot and am adding... The built-in Access data engine did not work for me to connect with a DNS-free connection. The code shows that it's using ActiveX Data Objects (ADO). You need to add a reference to that in your VBA project:
' For the account, use everything after https:// up to and including
' snowflakecomputing.com in your URL when connecting to Snowflake using the web UI.
Const SNOWFLAKE_ACCOUNT = "<your_account>.<your_region>.snowflakecomputing.com"
Const SNOWFLAKE_USER = "greg"
Const SNOWFLAKE_PASSWORD = "xxxxx"
Public Sub Main()
Dim odbc As String
Dim sfCon As ADODB.Connection
Set sfCon = OpenDatabaseConnection(GetConnectionString())
If Not sfCon Is Nothing Then
'Use the connection here...
sfCon.Close
End If
End Sub
Private Function GetConnectionString()
GetConnectionString = "Driver={SnowflakeDSIIDriver}" + _
";server=" + SNOWFLAKE_ACCOUNT + _
";uid=" + SNOWFLAKE_USER + _
";pwd=" + SNOWFLAKE_PASSWORD + _
";network_timeout=60" + _
"login_timeout=60"
End Function
Public Function OpenDatabaseConnection(ConnString As String) As ADODB.Connection
On Error GoTo Handler
Dim database As ADODB.Connection
Set database = New ADODB.Connection
With database
.ConnectionString = ConnString
.ConnectionTimeout = 60
.Open
End With
Set OpenDatabaseConnection = database
Exit Function
Handler:
MsgBox "Error: " + Err.Description
End Function
I am trying to remove all of the records from an SQL table in VB.net. My code for doing this is:
Dim SQL As String = "DELETE FROM MTable"
Using CN As New OleDb.OleDbConnection(AddPage.DBConnect)
CN.Open()
Dim DBcmd As New OleDb.OleDbCommand(SQL, CN)
DBcmd.ExecuteNonQuery()
CN.Close()
End Using
'SQLDataset.Tables("Mtable").Clear()
MtableTA.Update(SQLDataset)
SQL = "DELETE FROM ITable"
Using CN As New OleDb.OleDbConnection(AddPage.DBConnect)
CN.Open()
Dim DBcmd As New OleDb.OleDbCommand(SQL, CN)
DBcmd.ExecuteNonQuery()
CN.Close()
End Using
' SQLDataset.Tables("ITable").Clear()
ITableTA.Update(SQLDataset)
The Mtable and Itables are the SQL tables, while MtableTA and ItableTA are table adapters.
I also end up getting an error which states
An unhandled exception of type 'System.Data.DBConcurrencyException' occurred in System.Data.dll
Additional information: Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.
The section where this occurss is not provided in the code above, but is a call to MtableTA.update(SQLDataset). Any help would be very much appreciated. I'm also using OLEDB if that helps.
You have directly deleted the rows bypassing the TableAdapter methods to do that. So it is highly probable that when you call the Update there are some conflicts with data changed on the TableAdapter and no more available in the database.
After removing the rows directly using OleDbCommand.ExecuteNonQuery you should simply refresh the TableAdapters to sync them with the real situation on your physical database table
SQLDataset.Tables("ITable").Clear()
ITableTA.Adapter.Fill(SQLDataSet.ITable)
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
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.