Programming for MySql and MSSql in VB.NET - mysql

I have a program written in VB.NET that as part of its function requires the use of a number of database classes.
At the moment the classes are programmed specifically to use objects originating from System.Data.SqlClient and classes such as SqlConnection, SqlCommand, SqlParameter and SqlDataAdapter are used.
My aim is to use the analogous classes from Mysql.Data.MySqlClient (obtained via the Connector/Net download on the MySQL site). These for example would be: MySqlConnection, MySqlCommand, MySqlParameter and MySqlDataAdapter.
Is there some way in the code that I could maybe specify an abstract version of the classes (something like AbstractSqlCommand, AbstractSqlParameter) and be able to pick the correct implementation between SqlCommand and MySqlCommand based on the use of some other config variable.
Dim command As New AbsSqlCommand(sql, connection)
For Each p As AbsSqlParameter In param
command.Parameters.Add(p)
Next
Dim timeout As Integer = 3000
command.CommandTimeout = timeout
Try
connection.Open()
Catch
Throw New Exception("Connection failed")
End Try
Dim Adapter As New AbsSqlDataAdapter(command)
Adapter.Fill(table)
Return table
So in the case above some kind of global or configuration variable could be ussed to differentiate between whether AbsSqlCommand is actually used as a MySqlCommand or a SqlCommand [MSSQL] without the need for having to recode every instantiation of these objects to suit the particular database platform.

This is really a broad question that will be best answered by a full article like this, but look at
System.Data.Common Namespace
The classes in System.Data.Common are intended to give developers a
way to write ADO.NET code that will work against all .NET Framework
data providers.

Well you could have two linq to sql instances (there is no constraint on the number of instances and calsses there in), but I have no experince of using linq2sql with MySQL so I dont know how well it works. Id be inclined to set up a test project add a linq2sql setofdatatclesses and try to connect to a MySQL database, see what happens)

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.

VB.NET Datatable to Mysql

I'm creating an application which allows you to manage various data. The application is designed to work in a network, and thus in multi-user. For this reason I decided to trust the Datatable.
I have a class created by me for the management of operations MYSQL Database but now I still can not create a streamlined process to send the datatable to MySQL database.
Currently I am so
Dim SQLStm As String
'variable for sql query
Dim SQLManager As New ER.DB.ERMysql
For Each Riga In Datatable.Rows
'example query
SQLStm = "INSERT INTO test(Name,Phone)VALUES(Riga("Name"),Riga("Phone"))"
Try
Dim CMD As New MySqlCommand
CMD.Connection = connection
CMD.CommandText = SQLStm
CMD.ExecuteNonQuery()
Catch ex As Exception
End Try
Next
End Sub
or skim all the rows and gradually sending to the database. There is a better way to accomplish this?
Thanks to all
I would say the best way to do this would be via XML. Convert the datatable to xml format and pass it through to a procedure which accepts an XML. This saves the process from running once per every line within a datatable, and it is all done in one go. The current way you are doing this would not scale well for large data sets, but XML would scale far better.
instead performing a db insert for each row, build the whole query string first and then perform it as one large INSERT command. It's much faster.

.Net Application for Creating SP's in SQl

I want to create a Dot net application and provide an environment to a user may be Multiline Text box, where user can Paste the predefined SP and Execute. After execution this Sp should be created in DB
Any ideas are invited..
I assume you want to do thid for a internal support application or something like that, not to the end-user, right?
Anyway, you need to be more specific, but the way you would create a procedure doesnt differ the way you would run a insert statment for example.
Simple example:
SqlConnection objConnection = new SqlConnection(your_connection_string);
SqlCommand objCommand = new SqlCommand(tbProcedureCode.text, objConnection);
objCommand.CommandType = CommandType.Text;
objConnection.Open();
objCommand.ExecuteNonQuery();

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

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

Whats the proper way to do explicit transactions with linq to sql?

I have some scenarios where I need to have multiple calls to .SubmitChanges() on a datacontext, but I want to explicitly control the transaction myself to make it atomic. For a while I have been doing this by creating a connection, creating a transaction on that connection, then creating the datacontext and passing it both. Lets assume for now I dont want to use TransactionScope instead. My code looks like this:
Using conn As New SqlConnection("connection string...")
conn.Open()
Using trans = conn.BeginTransaction()
Dim dc as new DataContext(conn)
dc.Transaction = trans
' do some work
trans.Commit()
End Using
End Using
I began using the Linq To SQL profiler and it breaks this code. For some reason they require you to use the .Connection property on the datacontext to create the transaction. It fails if you use the connection variable directly (which I think is silly). My question is, is it more appropriate to do it this way:
Using conn As New SqlConnection("connection string...")
conn.Open()
Dim dc as new DataContext(conn)
Using trans = dc.Connection.BeginTransaction()
dc.Transaction = trans
' do some work
trans.Commit()
End Using
End Using
Which is the more widely accepted way to do this?
The second snippet doesn't seem appropriate to me. With the second snippet you need to create the transaction after creating the context, which is -at least- from a readability / maintainability perspective less useful. I try to imagine how your code would look when you need to create two DataContext classes, and create the transaction (only) after creating the first context. This makes it pretty hard to keep clean separated code.
I think you should send a mail to Hibernating Rhinos and ask if they fix this bug.
Product prod = db.Products.Single(p => p.ProductID == 15);
if (prod.UnitsInStock > 0)
prod.UnitsInStock--;
using(TransactionScope ts = new TransactionScope()) {
db.SubmitChanges();
ts.Complete();
}
http://msdn.microsoft.com/en-us/library/bb425822.aspx
use TransactionScope
http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx
http://www.codeproject.com/KB/dotnet/TransactionScope20.aspx