Database Programming in C# with MySQL : Using OleDB - MySQL Access in the Real World
(Page 4 of 4 )
The example I will be developing will primarily focus on a class that returns OleDbConnection, OleDbCommand and OleDbDataReader instances. It contains two classes: Data, which creates and returns instances of OleDbConnection, OleDbCommand and OleDbDataReader; and DataTest, which tests the functionalities provided by the Data class.
Let's start with the Data class. Its parameterized constructor creates the connection string from the parameters passed and instantiates the OleDbConnection connection class using the string. The getDataReader method returns an OleDbDataReader instance based on the OleDbCommand instance passed. Here is the class:
using System;
using System.Data;
using System.Data.OleDb;
namespace MySQLApp
{
/// <summary>
/// Creates and returns OleDbConnection, OleDbCommand
/// and OleDbDataReader
/// </summary>
public class Data
{
private OleDbConnection connection=null;
private OleDbCommand command=null;
string connectionString=null;
public Data()
{
connectionString="";
}
public Data(string host, string userId, string password)
{
connectionString=" Provider=MySqlProv; Data Source="+host+"; User id="+userId+"; Password="+password+";";
connection=new OleDbConnection(connectionString);
command=new OleDbCommand();
}
public OleDbCommand getCommand(string sqlString)
{
command.Connection=connection;
command.CommandText=sqlString;
return command;
}
public OleDbDataReader getReader(OleDbCommand command)
{
return command.ExecuteReader();
}
}
}
The next class is DataTest. It creates an instance of the Data class and executes a SQL statement using it. Here is the code:
using System;
namespace MySQLApp
{
/// <summary>
///Creates an instance of Data class to execute a
///simple SQL statement.
/// </summary>
class DataTest
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Data data=new Data("localhost","root","root123");
data.getReader(data.getCommand("select * from
user"));
while( reader.Read())
Console.WriteLine(reader.GetString(1));
}
}
}
That brings us to the end of this discussion. The application developed here will form the basis of advanced operations using DataAdapter in the next part of this discussion. Till then…
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |