119-c-sharp-sqlconnection-and-sqlcommand-class

Easier way to access database from C# is to

If we connect to databases in C# directly, two additional namespaces are necessary:
using System.Data.SqlClient;
using System.Collections;
In our C# program, we need to use c sharp SqlConnection and c sharp SqlCommand class objects. We assume that we already have database with only one table and that this table contains address book data. We can name this table as “PERSON”. Columns are following:
1. ID_PERSON
2. NAME
3. SURNAME
4. PHONE
5. EMAIL

public partial class Form1 : Form
{

public Form1()
{

InitializeComponent();

}

SqlConnection sqlCn = new SqlConnection(“Data Source=Database1.sdf”);
SqlCommand sqlCmd = new SqlCommand();
ArrayList alConnection = new ArrayList();

private void Form1_Load(object sender, EventArgs e)

{

}

}

note: if Microsoft SQL Server 2008 database connection was used, this would be and example of SqlConnection object:
SqlConnection cn = new SqlConnection(“Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\C#\\documents\\visual studio 2010\\Projects\\06_01\\06_01\\Address.mdf;Integrated Security=True;User Instance=True”);

See details on connectionstrings.

In this simple application we would use one ListBox (ltbxPersons) control and several TextBox-es and command buttons. We will prepare private void function for displaying content from “PERSON” table, and call it from form load event.

private void list_of_persons()
{

ltbxPersons.Items.Clear();
alConnection.Clear();

string str_sql_query = “select * from PERSON”;
sqlCmd.Connection = sqlCn;
sqlCn.Open();
sqlCmd.CommandText = str_sql_query;
SqlDataReader sqlrdReader = sqlCmd.ExecuteReader();
while (sqlrdReader.Read())
{

ltbxPersons.Items.Add(sqlrdReader[“NAME”].ToString() + ” ” + sqlrdReader[“SURNAME”].ToString());
alConnection.Add(sqlrdReader[“ID_PERSON”]);

}
sqlCn.Close();

}

private void Form1_Load(object sender, EventArgs e)
{

list_of_persons();

}

In here, ListBox ltbxPersons takes SQL query results for “NAME” and “SURNAME” columns, while ArrayList alConnection takes ID’s (“ID_PERSON”).

External links:

C sharp SqlConnection and SqlCommand on Daniweb
C sharp SqlConnection and SqlCommand on Microsoft
C sharp SqlConnection and SqlCommand on Csharp-station

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*