How do I establish a connection to MySQL via VB & display simple query results on a form? - mysql

I have a project in Visual Studio 2008 and there is a working data connection to a MySQL database. In other words, I can query the db directly from Visual Studio and it will display the results.
I've tried a couple of approaches that I found online for writing a connection string and accessing the db, but no luck yet.
All I'm trying to do is code a button to query the db and then reset the text property of a label/textbox to display the results based upon another label/textbox value.
The pseudo-code I am imagining is something like this:
Private Sub query_submit_button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles query_submit_button.Click
result_textbox.Text = SELECT field FROM table WHERE otherfield = key_textbox.Text
End Sub
I didn't see any related questions posted on SO - forgive me if I missed one that already exists and this is a dupe.
What is the correct way to accomplish this?
EDIT
Using MySQL 5.1

You can download the ODBC Provider and then reference, import, and use it to query the database through a ODBCCommand instance.
'Put this at the very top of your .VB file...
Imports System.Data.ODBC
'Put this in some method in your code when you are ready to query the DB...
Using connection As New OdbcConnection(connectionString)
Dim command As New OdbcCommand(strSqlQuery, connection)
connection.Open()
result_textbox.Text = command.ExecuteScalar.ToString
End Using

i used DaMartyr's answer to get 99% there, but needed to add this declaration:
Dim connectionString As String = "driver={MySQL ODBC 5.1 Driver};server=SERVER;uid=USERID;pwd=PASSWORD;database=DATABASE"
just replace the SERVER, USERID, PASSWORD, & DATABASE with your personal settings

Related

Visual Basic 2010: How to check if data is already in the SQL database?

I'm using Microsoft Visual Basic 2010 Express and SQL Server 2008. I already connected the database I created and managed to input data on in. Im making a very simple registration system where I only put a idNumber and the password. The problem is I have to make the system detect whether the idNumber was already registered then executes a statement.
Imports System.Data.SqlClient
Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=MYDATASOURCE;Integrated Security=True")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
cmd.Connection = cn
cn.Open()
'this is where to put the code the search the database i think..
cn.Close()
Ive been looking for days and it seems like vb.net is mostly used and answered but I have to use visual basic. I have no idea what code to put in there to read the database. I do think like c++ I have to retrieve the data and declare in on a variable then that is when I search it.
I can provide you brief guidelines, but you need to do due diligence to accomplish this.job.
Write a stored procedure IsIdNumberExists that will check whether a idNumber exists in database tablet. Something like this....
var #recCount
Select #recCount = count(1) from yourTable where idNumber=#inputidNumber // pass it from UI
if #recCount=0
return false
return true
2 In your C# code, pass StoredProcedure name to cmd object.
3 Create a SqlParameter and attach it to cmd object
4 Execute cmd.ExecuteNonQuery();
5 Get the return boolean object in C# and decide accordingly.

What Could Be Causing Crystal Report in Visual Studio 2010 To Display Gibberish?

Good morning,
After watching numerous online tutorials and reading the Documentation, I decided to get hands on with the Crystal Reports for Visual Studio runtime. It is my understanding that the SAP Crystal Reports runtime doesn't natively support connections to a MySQL DB so I believe I've done everything correctly to pull the DB records into a Dataset object. I can see the records in the Dataset and they match what's in the Database. Unfortunately, when I run a preview of the report everything is "gibberish" except for the Date fields.
I'm stumped and don't know what to do now, any assistance would be greatly appreciated. Screenshots below show the records from the Dataset as well as the Report preview.
By the way, the Collation on the server and table are both set to "Latin1 - Default Collation" - not sure if that makes any difference.
IMAGE #1: VIEW OF DATASET RECORDS
Click here for a larger image: https://dl.dropbox.com/u/55174425/Dataset%20Records.jpg
IMAGE #2: DESIGN VIEW OF REPORT
Click here for a larger image: https://dl.dropbox.com/u/55174425/Design%20View%20of%20Report.jpg
IMAGE #3: PREVIEW OF REPORT
Click here for a larger image: https://dl.dropbox.com/u/55174425/Preview%20of%20Report.jpg
Hello SO,
I managed to answer my own question and decided to share my answer in case somebody out there runs into this same problem.
Well, it's not so much a problem as it is the actual way the Crystal Reports for Visual Studio runtime is supposed to work (at least when it comes to MySQL). What I didn't realize was that, because the CR runtime for VS didn't support a native connection to a MySQL database, it was necessary to use Visual Studio to create a Server Connection using the .Net Connector (which is made available when you install the Connector).
Once the server connection was made, I was then able to create a DataSet and populate it with the records from the DB. Unfortunately, what I didn't realize was that this dataset simply allows for the selection of the fields/columns necessary for the designing of the report (.rpt file). Now, here's where my "gibberish" problem was. In fact, I discovered that the CR runtime purposefully uses random text/characters when you're designing the report and if you preview the report you will see this. Also, if you debug the application you will get a blank report with only the column headers.
The solution to this is to programatically query the DB, create and fill a DataTable and assign it to a new instance of the report you just created as its datasource. And viola, the report now shows the information I was looking for. So, here's the code I ended up using at run-time in order to get my report to display the data I was looking for:
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
'Define the MySQL Connection String.
Dim myConnectionString As String = "Server=server_address;Port=3306;Uid=user_id;Password=password;Database=schema_name;"
'Create a new MySqlConnection object and assign the Connection String to it.
Dim dbConn As New MySqlConnection(myConnectionString)
'Define your Query.
Dim dbQuery As String = "SELECT * FROM users"
'Create a new MySqlDataAdapter object and assign the Query and Connection String objects to it.
Dim dbAdapter As New MySqlDataAdapter(dbQuery, dbConn)
'Create a new DataTable object and fill it with the contents of the MySqlDataAdapter object.
Dim dbTable As New DataTable
dbAdapter.Fill(dbTable)
'Create a new instance of the report you previously designed and set its DataSource to the DataTable.
Dim report As New rptUserList
report.SetDataSource(dbTable)
'Set the ReportSource of the CrystalReportViewer control to your report.
CrystalReportViewer1.ReportSource = report
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

mySQL-query from Microsoft Access VBA fails if not interactive?

I'm fighting with a VBA non-interactive problem that really bugs me: I have a pass-through query to a mysql database, which works well if double-clicked by the user. But it fails if called from VBA automation session (called from excel) if no interaction was done first. Most strange: it works from VBA after clicking it on the GUI for a while (odbc mysql connection timeout possibly).
The passthrough-query has it's password in the DSN and in the connection string (to sort out problems with the store). The behavior is the same with a linked table.
Problematic VBA code called looks like this:
CurrentProject.Connection.Execute "INSERT INTO [SomeLocalTable] (id) SELECT id FROM [somePassThroughOrLinkedMySQLTable]"
The error is a generic odbc connection failure 80004005.
While this type of query works all the time:
Dim cnn As New ADODB.Connection
cnn.Open ("Driver=MySQL ODBC 5.2w Driver;SERVER=myserver;UID=user;DATABASE={db};PORT=3306;DFLT_BIGINT_BIND_STR=1;PWD=secret")
Can I "initialize" the passthrough query like the UI does to make it work? Or can I use the second type of query to insert into a local MS Access table?
Environment: Win8-64bit, Office2013, mysql-odbc-5.2w
I think the problem is happening because you are referring to the Access database as an external ADODB data source, instead I would use an instance of Access in order to run the query via DAO. The sample sub below creates an invisible instance of Access and executes the query, and then quits once finished. I've used late binding in this example with DAO version 3.6 so you may need to amend that bit slightly or use early binding:
Sub ExecPassThru()
Dim acApp As Object
Dim acDb As Object
Set acApp = CreateObject("Access.Application")
Set acDb = CreateObject("DAO.DBEngine.36") 'May need slight alteration
acApp.OpenCurrentDatabase ("C:\db1.mdb") 'Amend as required
Set acDb = acApp.CurrentDb
acDb.Execute "INSERT INTO [SomeLocalTable] (id) SELECT id FROM [somePassThroughOrLinkedMySQLTable]"
acDb.Close
acApp.Quit 2
End Sub
This was coded using Excel 2003 but should be easy enough to translate to later versions of office.

how to import/attach sql server compact edition tables/relationships with microsoft Access?

I need to move my Sql Server CE database into MS Access, so my users who are familiar with Access can run queries on the data. Is there a free way to do that?
Thanks!
David
You have two options, you can either import the data into access or link the tables in access so the data stays in SQL CE and is just referenced by access.
I don’t think access can import it directly so you will have to make an ODBC connection to your CE file using the ODNC admin program in windows. Once you have done that you can move onto the next step
On the file menu go to get external data and then either import or link depending on what option you want, on the next dialog box select ODBC databases as the file type and select the ODBC connection you just made.
Follow the on screen prompts from there and Roberts your mothers brother
EDIT:
Sorry yes I did mean ODBC, my finger must have slipped on the keyboard. Anyway Yes it looks like the ODBC driver does not exist however a OLEDB driver does so you could open up the database in code using ADO and either manipulate it there or loop through each table and insert it into an access table you created earlier. Here is some code showing how to open a SQL CE recordset in VBA
Sub test()
Dim pConn As ADODB.Connection
Dim pRS As ADODB.Recordset
Set pConn = New ADODB.Connection
Dim cmd As New ADODB.Command
Set pRS = New ADODB.Recordset
' For 3.0 use PROVIDER=Microsoft.SQLSERVER.MOBILE.OLEDB.3.0
pConn.ConnectionString =
"PROVIDER=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=C:\Northwind.sdf"
pConn.Open
cmd.ActiveConnection = pConn
cmd.CommandText = "SELECT * FROM Products"
Set pRS = cmd.Execute
' Open the recordset
While Not pRS.EOF
Debug.Print pRS(0)
Debug.Print pRS(1)
pRS.MoveNext
Wend
End Sub

Connect SQL Server Compact 3.5 Database to MS Access 2003 using ADO?

Is it possible to write connect and open a SQL Compact 3.5 database from within MS Access 2003? I want to be able to use MS Access 2003 to manipulate data in a SQL Compact 3.5 database. If it is possible, then what statements would be used to open the database?
This is just an idea and I can't confirm that it will work, but given that SQL Compact lacks an ODBC driver and you can't have linked tables, perhaps you can use an OLEDB connect string for SQL Compact as the Source Connect String of a saved QueryDef in Access. If you can get that to work you may be able to create a saved QueryDef for each table, and then utilize them as though the queries were linked tables.
I can't test it on my machine because the only OLEDB provider I have installed is Jet, and Access doesn't seem to like that.
But it might be worth a try. Possibly it's not going to work, as I can't find anywhere that anyone has done this in Access. But I don't really see why it shouldn't work.
Again, I could simply be wrong, though.
Though I did not try it specifically with SQL Compact, connecting to the server should be standard:
Check that the ADODB file (msado21.tlb) is correctly refernced in your available tools
Write down your connection string somewhere like this one:
MyConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=YourDatabaseName;Data Source=YourSQLServerInstanceName"
This string is written for an 'integrated security' context. In cas you want to change it for an SQL security context, please check here to update the string. Ideally, this string should be declared as a public variable in your code.
Once this is done, you can open an ADODB recordset and begin to manipulate it:
public sub connectionTest
Dim activeConnection as ADODB.connection, _
activeRecordset as ADODB.recordset
Set activeConnection = New ADODB.connection
activeConnection.connectionString = myCOnnectionString
activeConnection.open
set activeRecordset = New ADODB.recordset
'this will open a read-only recordset'
activeRecordset.open _
"SELECT * FROM myTableName", _
activeConnection, _
adOpenStatic, _
adLockReadOnly
if activeRecordset.EOF and activeRecordset.BOF then
debug.print "No records in this table"
else
activeRecordset.moveFirst
do while not activeRecordset.EOF
debug.print activerecordset.fields("myFieldName").value
activeRecordset.moveNext
loop
endif
activeRecordset.close
set activeRecordset = nothing
activeConnection.close
set activeConnection = nothing
end sub