Monday, August 11, 2008

ODBC , OLEDB and SQLClient database connection using c#.net with some Stored Procedures

  • This article is for basic learners that need to know about database connectivity using C#.net with OLEDB,ODBC and SQLClient.
  • AddItems and DeleteItems buttons use stored procedures to insert and delete data.
  • This is the screen shot of the simple application.




 ==================start code example=================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace ZONE
{
public partial class Form1 : Form
{

///
/// my database server running on my machine.
///

string OLEDBString="Provider=SQLNCLI;Server=.;Database=zone;Trusted_Connection=yes;";

string ODBCString="Driver={SQL Native Client};Server=.;Database=zone;Trusted_Connection=yes;";

string constring="";
public Form1()
{
InitializeComponent();
}

--------------------------------------------------------------------------------

private void Form1_Load(object sender, EventArgs e)
{
rdbODBC.Checked = true;
fillGrid();
}

--------------------------------------------------------------------------------

private void btnadd_Click(object sender, EventArgs e)
{
string s1 = txtId.Text;
string s2 = txtname.Text;
string s3 = txtage.Text;
string s4 = txtsex.Text;

if (rdbODBC.Checked)// Check whether the “ODBC Radio Button” is checked or not
{
OdbcConnection con = new OdbcConnection();
con.ConnectionString = constring;// assign odbc connection string
OdbcCommand cmd = new OdbcCommand();
try
{

con.Open();

cmd.Connection = con;

cmd.CommandText = "INSERT INTO EMPLOYEE(empID,empName,empAge,empSex) VALUES('" + s1 + "','" + s2 + "','" + s3 + "','" + s4 + "')";

cmd.ExecuteNonQuery();

cmd.Parameters.Clear();

dgrid1.Refresh();

fillGrid();

dgrid1.Refresh();

MessageBox.Show("Successfully Inserted.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();

}
}
else if (rdbOLEDB.Checked)// Check whether the “OLEDB Radio Button” is checked or not
{
OleDbConnection con2 = new OleDbConnection();
con2.ConnectionString = constring; // assign oledb connection string
OleDbCommand cmd2 = new OleDbCommand();

try
{
con2.Open();

cmd2.Connection = con2;

cmd2.CommandText = "INSERT INTO EMPLOYEE(empID,empName,empAge,empSex) VALUES('" + s1 + "','" + s2 + "','" + s3 + "','" + s4 + "')";

cmd2.ExecuteNonQuery();

cmd2.Parameters.Clear();

dgrid1.Refresh();

fillGrid();

dgrid1.Refresh();

MessageBox.Show("Successfully Inserted.");

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con2.Close();
}
}
}

----------------------------------------------------------------------------

private void btnDelete_Click(object sender, EventArgs e)
{
string s1 = txtId.Text;

if (rdbODBC.Checked)// Check whether the “ODBC Radio Button” is checked or not
{
OdbcConnection con = new OdbcConnection();

con.ConnectionString = constring;// assign the odbc connection string

OdbcCommand cmd = new OdbcCommand();
try
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "DELETE FROM EMPLOYEE WHERE empID='" + s1 + "'";
cmd.ExecuteNonQuery();

dgrid1.Refresh();
fillGrid();
dgrid1.Refresh();

MessageBox.Show("Successfully Deleted.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
dgrid1.Refresh();
}
}

else if (rdbOLEDB.Checked)// Check whether the “OLEDB Radio Button” is checked or not
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = constring;// assign oledb connection string
OleDbCommand cmd = new OleDbCommand();
try
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "DELETE FROM EMPLOYEE WHERE empID='" + s1 + "'";
cmd.ExecuteNonQuery();

dgrid1.Refresh();
fillGrid();
dgrid1.Refresh();

MessageBox.Show("Successfully Deleted.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}

}
}

------------------------------------------------------------------------------

private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}


-------------------------------------------------------------------------------


public void fillGrid()
{
if (rdbODBC.Checked)// Check whether the “ODBC Radio Button” is checked or not
{
OdbcConnection con = new OdbcConnection();
con.ConnectionString = constring;// assign odbc connection string
OdbcCommand cmd = new OdbcCommand();
DataTable dt = new DataTable();
OdbcDataAdapter adap = new OdbcDataAdapter();
try
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM EMPLOYEE";
adap.SelectCommand = cmd;
adap.Fill(dt);
adap.SelectCommand.ExecuteNonQuery();

dgrid1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
else if (rdbOLEDB.Checked)// Check whether the “OLEDB Radio Button” is checked or not
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = constring;// assign oledb connection string
OleDbCommand cmd = new OleDbCommand();
DataTable dt = new DataTable();
OleDbDataAdapter adap = new OleDbDataAdapter();

try
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM EMPLOYEE";
adap.SelectCommand = cmd;
adap.Fill(dt);
adap.SelectCommand.ExecuteNonQuery();
dgrid1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}

}
txtId.Text = "";
txtage.Text = "";
txtname.Text = "";
txtsex.Text = "";
}


-----------------------------------------------------------------------------


private void rdbODBC_CheckedChanged(object sender, EventArgs e)
{
constring = ODBCString;// assign odbc connection string
}


--------------------------------------------------------------------------------


private void rdbOLEDB_CheckedChanged(object sender, EventArgs e)
{
constring = OLEDBString;// assign oledb connection string
}


--------------------------------------------------------------------------------


private void addProcedure_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();

con.ConnectionString = "Server=.;Database=zone;Trusted_Connection=True;";

try
{
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.addEmployeeData";// my add procedure name

cmd.Parameters.Add("@empID",SqlDbType.Int).Value = txtId.Text;
cmd.Parameters.Add("@empName", SqlDbType.NVarChar).Value = txtname.Text;
cmd.Parameters.Add("@empAge", SqlDbType.NVarChar).Value = txtage.Text;
cmd.Parameters.Add("@empSex", SqlDbType.NVarChar).Value = txtsex.Text;

cmd.ExecuteNonQuery();

fillGrid();

MessageBox.Show("Execute procedure with no errors.Added successfully.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}


-------------------------------------------------------------------------------


private void btnDeleteProcedure_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
con.ConnectionString = "Server=.; Database=zone; Trusted_Connection=yes;";

try
{
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.deleteEmployeeData";// my delete procedure name
cmd.Parameters.Add("@empID", SqlDbType.Int).Value = txtId.Text;

cmd.ExecuteNonQuery();

fillGrid();

MessageBox.Show("Execute procedure with no errors.Deleted successfully.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}

=====================End code example================

***************************************************************

==================start procedure [addEmployeeData]=======
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


-- =============================================
-- Author: lalindu
-- Create date:
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[addEmployeeData]
-- Add the parameters for the stored procedure here
@empID int ,
@empName nvarchar(100) ,
@empAge nvarchar(50) ,
@empSex nvarchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
INSERT INTO EMPLOYEE(empID,empName,empAge,empSex)
VALUES(@empID,@empName,@empAge,@empSex);
END

=================End Procedure [addEmployeeData]===========

===================start procedure [deleteEmployeeData]=======

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

-- =============================================
-- Author: Lalindu
-- Create date: 2008-08-11
-- Description: Delete from the table
-- =============================================
ALTER PROCEDURE [dbo].[deleteEmployeeData]
-- Add the parameters for the stored procedure here
@empID int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
DELETE FROM EMPLOYEE WHERE empID=@empID;
END

===================End Procedure [deleteEmployeeData]==========

Tuesday, July 31, 2007

How to write and read XML file using VB.NET

How to read and write Existing XML file Using VB.NET
------------------------------------------------------------------------------------------------

Imports System.Data.DataSet

Public Class SettingsXML

Dim XML_FILE_PATH As String = "C:\XMLData.xml"

Dim xmldataset As New Data.DataSet

Sub WriteXML(ByVal ServerIP As String, ByVal Name As String, ByVal Age As String, ByVal SignaturePath As String, ByVal NotifyTimer As Integer, ByVal Timer As Integer)
again:
Try

xmldataset.ReadXml(XML_FILE_PATH)

xmldataset.Tables(0).Rows(0).Item("ServerIP") = ServerIP
xmldataset.Tables(0).Rows(0).Item("Name") = Name
xmldataset.Tables(0).Rows(0).Item("Age") = Age
xmldataset.Tables(0).Rows(0).Item("SignaturePath") = SignaturePath
xmldataset.Tables(0).Rows(0).Item("NotifyTimer") = NotifyTimer
xmldataset.Tables(0).Rows(0).Item("Timer") = Timer

xmldataset.AcceptChanges()
xmldataset.WriteXml(XML_FILE_PATH)
xmldataset.Dispose()

Catch ex As Exception

'MsgBox("XML Error" & ex.ToString)
Dim xmlfile As New CreateXMLFile()
xmlfile.WRITEXML()
GoTo again
End Try

End Sub
Function ReadXML(ByVal a As Integer) As String
again:
Try
xmldataset.ReadXml(XML_FILE_PATH)
If a = 0 Then
Return xmldataset.Tables(0).Rows(0).Item("ServerIP")
End If
If a = 1 Then
Return xmldataset.Tables(0).Rows(0).Item("Name")
End If
If a = 2 Then
Return xmldataset.Tables(0).Rows(0).Item("Age")
End If
If a = 3 Then
Return xmldataset.Tables(0).Rows(0).Item("SignaturePath")
End If
If a = 4 Then
Return xmldataset.Tables(0).Rows(0).Item("NotifyTimer")
End If
If a = 5 Then
Return xmldataset.Tables(0).Rows(0).Item("Timer")
End If
Catch ex As Exception
Dim xmlfile As New CreateXMLFile()
xmlfile.WRITEXML()
GoTo again
End Try
End Function

End Class

--------------------------------------------------------------------------------------------------

How to write a New XML File Using VB.NET


Public Class CreateXMLFile

Sub WRITEXML()
Dim mywriter As System.Xml.XmlTextWriter = New System.Xml.XmlTextWriter("C:\XMLData.xml", Nothing)
With mywriter
.Indentation = 4
.IndentChar = " "
.Formatting = .Indentation
.WriteStartDocument()
.WriteComment("Settings for the Connection")
.WriteStartElement("settings")
.WriteElementString("ServerIP", "192.168.1.42")
.WriteElementString("Name", "name")
.WriteElementString("Age", "25")
.WriteElementString("SignaturePath", "D:/sign")
.WriteElementString("NotifyTimer", "1")
.WriteElementString("Timer", "1")
.WriteEndElement() 'For settings
.WriteEndDocument()

End With
mywriter.Flush()
mywriter.Close()
End Sub
End Class



Monday, May 7, 2007