VB.NET MySQL Connection (DB not local) - mysql

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

Related

MySQL commands in vb code are not working

I've been trying to create a login page that will check if you're an administrator or a customer in my SQL data source. I am not sure why it can't understand the MySQLCommands. I added MySql.Data in the references but this doesn't seem to work.
This is where for example: MySqlConnection and MySqlCommand have blue underlinement.
Dim cmd As MySqlCommand = New MySqlCommand '(strSQL, con)
Password is a reserved word in MySql. If you want to use a field with that name then everytime you use it in your code you should remember to put it between backticks:
`password` = ...
Said that your code has serious problems. You should never concatenate strings coming from the user input to form a sql text. This leads to syntax errors caused by parsing problem and to Sql Injection attacks. You shoul use a parameterized query like this
strSQL = "SELECT name FROM employer WHERE (login=#login AND `password`=#pwd"
Dim cmd As MySqlCommand = New MySqlCommand(strSQL, con)
cmd.Parameters.Add("#login", MySqlDbType.VarChar).Value = strUser
cmd.Parameters.Add("#pwd",MySqlDbType.VarChar).Value = strPaswoord
con.Open()
If cmd.ExecuteScalar() = Nothing Then
....
Finally you should also change the way you get your data because you want to minimize the trips to access the database for performance reason. You should SELECT both the Name and the EMail with a single query and use an MySqlDataReader to get the data.
Other problems present in your code are the lack of appropriate using statement around the connection and the security problem caused by a possible clear text password stored in the database.
#GSerg asked me if I could right click and resolve.
I tried that but that was not an option.
After messing around with the error it appears that I had to write at top:
Imports MySql.Data.MySqlClient
I also had to add backticks when I used the word password for MySQL as #Steve reminded me.
Thank you for your help!

deleting items from sql table in VB.net

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)

Classic ASP global.asa SQL Server 2008 connection string

I have been given a web application written in Classic ASP to port from Windows 2003 Server (SQL Server 2000 and IIS 6) to Windows 2008 Server (SQL Server 2008 and IIS 7.5).
The site uses a GLOBAL.ASA file to define global variables, one of which is the connection string (cnn) to connect to SQL Server.
Below is the (old) connection string from GLOBAL.ASA:
Sub Application_OnStart
Dim cnnDem, cnnString
Set cnnDem = Server.CreateObject("ADODB.Connection")
cnnDem.CommandTimeout = 60
cnnDem.Mode = admodeshareexclusive
cnnString = "Provider=SQLOLEDB; Data Source=192.xxx.x.xx; User Id=xxxx; Password=xxxxx; default catalog=xxxxxxx;"
Application("conString")=cnnString
Call cnnDem.Open(cnnString)
Application("cnn") = cnnDem
End Sub
The .ASP pages then use the cnn value like this:
strSQL = "Select * From tblUtilities order by companyname"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQL, Application("cnn"), adOpenKeyset
However I could not get the connection string to connect – I whittled it down to a “Failed to Login” error message (no matter what Login ID I tried).
I edited the GLOBAL.ASA file as follows and it works.
Sub Application_OnStart
Dim cnnDem, cnnString
Set cnnDem = Server.CreateObject("ADODB.Connection")
cnnDem.CommandTimeout = 60
cnnString = "Provider=SQLNCLI10.1;User Id=xxxx; Password=xxxxx;Initial Catalog=xxxxxxx;Data Source=xxxxxx\SQLEXPRESS;"
Application("conString")=cnnString
Application("cnn")=cnnString
Call cnnDem.Open(cnnString)
End Sub
The main difference is that cnn now contains the connection string, where as previously cnn was an object referring to ADOBD.Connection.
The question I have is what impact (if any) will this have on the application. I have done some basic (local) testing and everything looks ok at the moment. But I am wondering if there might be multi-user issues (or something of that nature) that might arise when this site is deployed again.
One of the best and easiest way to connect to create a Database Connection String is to crease a new ASP file in the root directory or elsewhere and include the Connection string into it:
//Global.asp //
<%
Dim connectionString
connectionString = "PROVIDER=SQLOLEDB;DATA SOURCE=YourSQLServer;UID=sa;PWD=*******;DATABASE=YourDataBase"
%>
Then create an include statement in each file that you would like to call this connection.
<!-- #include virtual="global.asp" -->
Then, where you need to setup your connection call, simply use your code to connect to the Database:
<%
Set adoCon = Server.CreateObject("ADODB.Connection")
adoCon.Open = ConnectionString
Set rsReports = Server.CreateObject("ADODB.Recordset")
strSQL = "Select * From Customers"
rsReports.Open strSQL, adoCon
%>
I keep the Connection String in Global.asa but create the connection in a separate function loaded as needed. An Application connection object may not be aware of temporary network issues that may close that connection, and then future attempts to use the connection will not be successful.
Hope this makes sense.

Visual Basic 2005 + 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.

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.