Visual Basic 2005 + mysql - mysql

How do I connect to MySQL and get started with VB 2005?
Been using PHP + MySQL in work for bout a year now. Just wondering how to get started with Visual Basic 2005 + MySQL. Just to connect to a database, and run a simple select star query?
db -> db_name
table -> tbl_name
ip -> localhost

You can use the ADO.NET Driver for MySQL (Connector/NET), which you can download here:
http://www.mysql.com/products/connector/
After installing, you can use MySQL in the standard .NET way, using MySqlConnection, MySqlCommand, MySqlDataReader, and so on. The documentation is here:
http://dev.mysql.com/doc/refman/5.0/en/connector-net-programming.html
Some example code:
Dim myConnection As New MySql.Data.MySqlClient.MySqlConnection
myConnection.ConnectionString = "server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=test;"
myConnection.Open()
Dim myCommand As New MySqlCommand("select * from TheTable", myConnection)
Using myReader As MySqlDataReader = myCommand.ExecuteReader()
While myReader.Read()
Console.WriteLine((myReader.GetInt32(0) & ", " & myReader.GetString(1)))
End While
End Using
myConnection.Close()
The Using statement makes sure the data reader is closed when you no longer need it, even if an exception is thrown. You could also enclose the connection in a Using statement.

Related

ODBC connection string to Snowflake for Access Pass Thru Query

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

VB.NET MySQL Connection (DB not local)

I'm trying to connect to a MySQL server via VB.NET, but my program keeps freezing on the con.Open() line.
Imports System.Data.SqlClient
Imports System.Data
....
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Server=000.000.000.000;Database=db_name;Uid=db_user;Pwd=db_pw;"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT * FROM courses"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
MessageBox.Show(lrd.ToString)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server: " & ex.Message)
Finally
con.Close()
End Try
The stuff in the connection string is the form of what I have in those spots, using those words as actual value placeholders for this example. Apart from containing the actual values, they are exactly identical. So if there are form errors (i.e. a missing apostrophe), please let me know. For the Server, am I supposed to put the IP address of the server or something else? Furthermore, in the reading loop, I'm not sure how to display all of the contents of the SQL query. Is what I have correct?
You are using ADO.NET for SQL Server instead of what you should be using, an ADO.NET client that works with MySQL, like MySQL Connector
You will need to install this and change SqlClient, SqlCommand, SqlConnection in your code to MySqlClient, MySqlCommand, MySqlConnection in accordance with how the MySQL Connector works.
To display first column values:
While lrd.Read()
MessageBox.Show(lrd.GetValue(0))
End While

MySQL and ADO - hopeless?

Tearing hair out and googling all weekend. I am frantically converting an ASP site to use MySQL. Am I correct in thinking that I would be barking up the wrong tree to try to use recordset commands to get data in and out of MySQL via ODBC and should only use MySQL procedures? If so I face a nightmare, I think as have then to work out how to capture the returned values.
Sorry if this sounds hideously ignorant, but no idea where to turn.
DETAILS:
Set SConn = createobject("ADODB.Connection")
conn.open = "DRIVER={MySQL ODBC 5.1 Driver};"_
& "SERVER=" & SQLServer & ";"_
& "DATABASE=" & SQLDbase & ";"_
& "UID=" & SQLUser & ";PWD=" & SQLPW & "; OPTION=35;"
SQL = "SELECT tblNodes.SingleSiteChildID "
SQL = SQL & "FROM tblNodes "
SQL = SQL & "WHERE (((tblNodes.NodeID)=" & m_lngNodeID & "));"
set RS=server.CreateObject("adodb.Recordset")
RS.CursorType = 1
RS.LockType = 2
RS.Open SQL, conn
With RS
If not .Fields("SingleSiteChildID") >0 or isnull(.Fields("SingleSiteChildID")) then
If m_lngChildCount>0 then
.Fields("SingleSiteChildID")=0
m_lngSingleSiteChildID=0
Else
.Fields("SingleSiteChildID")=null
m_lngSingleSiteChildID=null
End if
.UPDATE
End if
END WITH
RS.Close
Set RS = Nothing
Set conn = Nothing
End Sub
You can use Recordset and Command objects in exactly the same way you are use other databases at the moment.
If you use DSNs, all you need to do is create a system DSN to the MySQL DB, although a DSN-less connection is a better way of doing it.
Head to the MySQL site to install the ODBC drivers then your connection string will look something like this:
Driver={MySQL ODBC 5.1 Driver}; Server=localhost; uid=user_name; pwd=password; database=db_name; option=67108899; port=3306;
Do a quick Google to check that the options specified there are correct for you, I have ripped this from a working Classic ASP site that uses MySQL.
Simply switching the connection string should allow you to migrate very simply to a new DB type. Do check that all your SQL commands conform to MySQL standards, and do not use words specific to MSSQL or Access, e.g. TOP is MS only, use LIMIT for MySQL.

Backslashes disapearing after my vb.net query to 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

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.