homeHome contactContact portfolioPortfolio musicMusic videoVideo historyHistory calendarCalendar rssRSS
karlpox | with GOD all things are possible

C# Add Update Delete

SELECT and INSERT data to database using C#

Example Table

Position
pos_id pos_name
1 Janitor
2 Guard

to SELECT data i created this class called connect and the method and properties below.

private SqlDataReader _select;
public SqlDataReader select
{
get
{
return _select;
}
set
{
_select = value;
}
}

public void query_select(string query)
{
SqlConnection c = new SqlConnection(@”Network Library=DBMSSOCN;Data Source=localhost;database=philguard;User id=karlpox;Password=12345;”);

c.Open();

SqlCommand q = new SqlCommand(query, c);

SqlDataReader r = q.ExecuteReader();

this.select = r;
}

to use we do this. Just call the query_select method and pass on your query(SQL statement) to be executed.

connect newConnect = new connect();
newConnect.query_select(”SELECT * FROM position”);
while (newConnect.select.Read())
{
listBox1.Items.Add(newConnect.select["pos_name"].ToString());
}

All rows returned will be added in the listbox.


Second to add datas into the database add this method to your class.

public void query_add(string query)
{
SqlConnection c = new SqlConnection(@”Network Library=DBMSSOCN;Data Source=localhost;database=philguard;User id=karlpox;Password=12345;”);

c.Open();

SqlCommand q = new SqlCommand();

q.Connection = c;

q.CommandText = query;

q.ExecuteNonQuery();

c.Close();
}

And to use this method we do this.

connect newConnect = new connect();
newConnect.query_add(”INSERT INTO position (pos_name) VALUES (`” textBox1.Text “`)”);

The statement above will add the data(textBox1.text) into your position database. Take note that pos_id is auto increment so you don`t have to specify it.

Connecting to MS SQL Server 2000 using C#

First is to create the connection string. You can store your connection string in a String data type.

Things that will be needed in your connection string is your Network Library, Data Source or the location of your database(ip), database the name of the database to be used, user id which is the username and lastly password.

For Example:

String cs = @”Network Library=DBMSSOCN;Data Source=localhost;database=test;User id=karlpox;Password=pogi;”

Next is to open a SQL connection. But you must import the sqlclient by adding this line to the top of your code.

using System.Data.SqlClient;

For Example:
SqlConnection c = new SqlConnection(cs);

Well these will let C# connect to the database. SQL statements not included in this post.