using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using MySql.Data.MySqlClient;
namespace testParamiterForMysql
{
public partial class Form1 : Form
{
string strConMysql = ConfigurationManager.ConnectionStrings["mySqlServer"].ToString();
Database Database = new Database();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Database.OpenConnection(strConMysql);
Database.OleDbCommand();
Database.BeginTransaction();
MySqlParameter startDat = new MySqlParameter("@startDate", textBox1.Text);
string sql = "INSERT INTO testtable(field1) VALUES (@startDate)";
Database.sqlCom.CommandType = CommandType.Text;
Database.sqlCom.Connection = Database.sqlCon;
Database.sqlCom.CommandText = sql;
if (!Database.DataManipulatewithparamiter())
{
Database.RollBackTran();
MessageBox.Show(Database.error);
return;
}
Database.CommitTran();
Database.CloseConnection();
}
}
}
Code (C#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
using System.Data.OleDb;
namespace testParamiterForMysql
{
class Database
{
public string error;
public MySqlCommand sqlCom = null;
MySqlTransaction Tran = null;
public MySqlConnection sqlCon = new MySqlConnection();
public void OpenConnection(string strCon)
{
if (sqlCon.State != ConnectionState.Open)
{
sqlCon.ConnectionString = strCon;
sqlCon.Open();
}
}
public void OleDbCommand()
{
if (sqlCon.State == ConnectionState.Open)
sqlCom = new MySqlCommand();
}
public void BeginTransaction()
{
Tran = sqlCon.BeginTransaction();
}
public bool DataManipulatewithparamiter()
{
try
{
sqlCom.Transaction = Tran;
sqlCom.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
public bool DataManipulate(string query, MySqlConnection sqlcon)
{
try
{
sqlCom = new MySqlCommand(query, sqlcon);
sqlCom.Transaction = Tran;
sqlCom.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
//tran.Rollback();
error = ex.Message;
return false;
}
}
public void CommitTran()
{
Tran.Commit();
}
public void RollBackTran()
{
Tran.Rollback();
}
public DataTable GetData(string strcon, string sqlstr)
{
return GetData(strcon, sqlstr, null);
}
public DataTable GetData(string strcon, string sqlstr, params MySqlParameter[] param)
{
MySqlConnection olecon = new MySqlConnection();
try
{
DataTable dt = new DataTable();
{
olecon.ConnectionString = strcon;
olecon.Open();
MySqlCommand dbCom = new MySqlCommand(sqlstr, olecon);
dbCom.Parameters.Clear();
if (param != null)
{
foreach (MySqlParameter p in param)
{
dbCom.Parameters.Add(p);
}
}
MySqlDataAdapter da = new MySqlDataAdapter(dbCom);
da.Fill(dt);
}
return dt;
}
finally
{
olecon.Close();
}
}
public void CloseConnection()
{
sqlCon.Close();
}
}
}
Tag : .NET, MySQL, Win (Windows App), C#, VS 2010 (.NET 4.x), Windows