A preserved archive of the Logical Gamers community forums, 2009-2025. The original threads and posts, served read-only. Registration, posting and private messages are gone for good.

VC# 2008 Express - MySQL Class

1.1k views · started by Chris ·
#1
VC# 2008 Express - MySQL Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using Microsoft.Data.Odbc;

namespace [color=Red][namespace][/namespace][/color]
{
class ODBC
{
private OdbcConnection Con;
private OdbcCommand ConDS;
public OdbcDataReader ConDR = null;

public bool Connect(String IP, String Password, String Database)
{
return Connect(IP, "3306", "root", Password, Database);
}

public bool Connect(String IP, String Username, String Password, String Database)
{
return Connect(IP, "3306", Username, Password, Database);
}

public bool Connect(String IP, String Port, String User, String Password, String Database)
{
try
{
Con = new OdbcConnection(@"Driver={MySQL ODBC 5.1 Driver};Server=" + IP + ";Port=" + Port + ";User=" + User + ";Password=" + Password + ";Database=" + Database + ";Option=3");
Con.Open();
}
catch
{
Con.Close();
return false;
}

return true;
}

public void Query(String SQL)
{
Query(SQL, false);
}

public void Query(String SQL, Boolean Read)
{
if (Con.State == ConnectionState.Open)
{
ConDS = new OdbcCommand(SQL, Con);

if (Read == true)
{
if (ConDR != null && ConDR.IsClosed.Equals(false))
{
ConDR.Close();
}

ConDR = ConDS.ExecuteReader();
}
}
}

public string Result(int Column)
{
if (ConDR != null && ConDR.IsClosed.Equals(false))
{
try
{
if (ConDR.Read())
{
return ConDR.GetValue(Column).ToString();
}
}
catch
{
return null;
}
}

return null;
}

public void FreeResult()
{
if (ConDR != null && ConDR.IsClosed.Equals(false))
{
ConDR.Close();
ConDR = null;
}
}
}
}



It's tested and works great!

Here is an example;

if (MySQL.Connect("localhost", "username", "password", "database"))
{
MySQL.Query("SELECT * FROM `test` WHERE `id` = '1';", true);

String Result = MySQL.Result(1);

if (Result != null)
{
MessageBox.Show(Result);
}

MySQL.FreeResult();
}



http://forum.logicalgamers.com/tutorials/8663-vc-2008-express-odbc-mysql-connection.html
#2
Looks pretty nice. Good job at coding it! if you did. >:3
#3
Chad wrote:
Looks pretty nice. Good job at coding it! if you did. >:3


Yeah I did, took a bit.

I have already managed to add a few functions into it, namely;

MySQL.Escape([query]);
MySQL.Fetch_Array();[/query]