Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
New MS SQL 2008 Available - DiscountASP.NET
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ADO.NET & Database » Using SQL in .NET: Part 1

Using SQL in .NET: Part 1

In this article, I will show you how to execute SQL queries from your C# applications.

Technologies: ADO.NET,Visual C# .NET
Total downloads :
Total page views :  11275
Rating :
 0/5
This article has been rated :  0 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
ArticleAd
Become a Sponsor



I usually see code samples using SELECT SQL queries but I don't see many articles using other SQL queries. In this article, I will show you how to execute SQL queries from your C# applications.

Before we go to SQL queries, we need to know how to make a connection to a database. I will use Sql data provider to connect to the SQL Server. The Sql data provider classes are defined in the System.Data.SqlCliet namespace and some general database related classes are defined in the System.Data namespace. Hence I import these two namespace in my application before writing any thing else.

using System.Data;
using System.Data.SqlClient;

Now let's create a connection object. The following code snippet creates a SqlConnection by using userid as sa and password as pass. After that code opens and closes the connection:

SqlConnection conn = new SqlConnection("Data Source=computer_name;"+"Initial Catalog=database_name;"+ "User ID=sa;"+"Password=pass;");
conn.Open();
conn.Close();

CREATE

I want to show you that it is fairly easy to use SQL queries in your application. In this article, I will explain the CREATE, INSERT, and SELECT queries.

Now if you wonder why do I start with the CREATE SQL query then the simple answer is I want to show you how to create a database and database table before you can select any data. Because to use the SELECT SQL query, you must have a database, database table, and data in the table.

The following source code shows you how to use the CREATE SQL query.

using System;
using System.Data;
using System.Data.SqlClient;
namespace SimpleSql
{
class CreateTable
{
[STAThread]
static void Main(string[] args)
{
// Make a SqlConnection and the Connection string as an argument
SqlConnection conn = new SqlConnection("Data Source=computer_name;"+ "Initial Catalog=database_name;"+ "User ID=sa;"+"Password=pass;");
/* Next thing we will do is make a sqlcommand so
* we can exucute our query
*/
SqlCommand cmd = new SqlCommand();
// We could give this as argument but that won't make our code real clear
cmd.CommandTimeout = 60; //
cmd.Connection = conn; // Sets wich connection you want to use
cmd.CommandType = CommandType.Text; // Sets the command type to use
cmd.CommandText = "CREATE TABLE simplesql "+"("+"simple_id int,"+"simple_text text"+")";
/* Why this approach you could write it in one line right???
* Yes you can you coudl make it like this
* "CREATE TABLE simplesql ( simple_id int, simple_text text )";
* most people would do it the simple way inclusive me :)
* but I want to make it real clear how to do it right
*/
// Next We will open the connection and make the query
try
{
conn.Open(); // Open the connection if it fails
// it will let you know with an exception
if (conn.State == ConnectionState.Open)
{
// Execute the query for this nothing is returned
cmd.ExecuteScalar();
Console.WriteLine("Table is Created");
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
finally
{
conn.Close(); // close the connection
}
Console.WriteLine("Press any key to quite");
Console.Read();
}
}
}

As you can see from the code, I have commented the code you can understand easily what's going on there.

The last thing we have to do is make a Primary key this is needed so that our simple_id can't have the same value twice "CREATE UNIQUE INDEX PrimaryID ON simplesql (simple_id)". Use this instead of the create table query.

NOTE:
I expected you to have a database available if you have not use this query instead of ours "CREATE DATABASE csharpcorner". Use this instead of the create table query. You also need to change the connection string delete this part from it "Initial Catalog=database_name;"+

INSERT

The INSERT SQL query is second most used queries. I think you have an idea what it is for. Yes, it's for inserting data into a database table. You will see how the INSERT query works in a momeny. The INSERT query works almost the same as the create statement but to make it more interesting I will make something for you so you get an idea of how you could do it for example a guestbook with asp.net.

  • We will make something to count of id already in the table to make an exclusive ID.
  • We let you type in the string to insert in the database

And here is the code:

using System;
using System.Data;
using System.Data.SqlClient;
namespace SimpleSql1
{
class Insert
{
[STAThread]
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Data Source=Computername;"+
// TODO: change comp name
"Initial Catalog=simplesql;"+"User ID=sa;"+"Password=pass;");
string strText = Console.ReadLine();
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 60;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Count(*) FROM simplesql";// Couldn't do it without sorry
conn.Open();
if (conn.State == ConnectionState.Open)
{
object objCount = cmd.ExecuteScalar();
int iCount = (int) objCount;
Console.WriteLine("Count was succesfull");
cmd.CommandText = "INSERT INTO simplesql (simple_id, simple_text) VALUES ("+ iCount +",'"+ strText +"')";
cmd.ExecuteScalar();
Console.WriteLine("Succesfully inserted the string");
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
finally
{
conn.Close();
}
Console.WriteLine("\n\n Press any key to quite");
Console.Read();
}
}
}

As you can see a little less comments but if you need any help with connection see the first code. I first let the user enter a string this was just to let you know how it works. For example you could make an application that has a Textbox in it en when clicking a button it will insert the string from the textbox to the table.
Next thing was count to count the numbers of rows in the database. I will explain this at the SELECT section because it uses a select query but you will know how it works in just a matter of minutes.
The select query is used like this and I will take our example for this
"INSERT INTO <table> (simple_text, simple_id) VALUES ('some text', 0)" NOTE that the order is reversed because we created the table like id, text
This would be the normal query "INSERT INTO <table> VALUES (1, 'some text')"
But I always use the first one this is because it will give you more control of how it is ordered.

SELECT

And at last after the though work with creating and inserting something to our database we will read it from it. I guess this is the most used command in SQL this because the query let you show you what's in the database. I will make a application that count the rows in the table this is because we need to know how long our for loop will be. This application will be more difficult then you already saw this article this because we also need a SqlDataReader for reading from the database.

I will first show you the code this code will be commented like the first one so read carefully

using System;
using System.Data;
using System.Data.SqlClient;
namespace SimpleSql1
{
class Select
{
[STAThread]
static void Main(string[] args)
{
/* we will first do the same thing
* connecting to the database as we did before
*/
SqlConnection conn = new SqlConnection("Data Source=computer_name;"+ "Initial Catalog=simplesql;"+"User ID=sa;"+"Password=pass;");
SqlDataReader dr;
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 60;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Count(*) FROM simplesql";
conn.Open();
if (conn.State == ConnectionState.Open)
{
object objCount = cmd.ExecuteScalar();
int iCount = (int) objCount;
Console.WriteLine("Count was succesfull \n");
cmd.CommandText = "SELECT simple_id, simple_text FROM simplesql ORDER BY simple_id";
dr = cmd.ExecuteReader(CommandBehavior.SingleResult);
Console.WriteLine("Succesfully Selected \n");
// For loop to read everything from the table
for (int i = 0; i < iCount; i++)
{
dr.Read(); // Read one row from the table
Console.WriteLine("ID: {0} \t Text: {1}", dr[0], dr[1]);
}
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
finally
{
conn.Close();
}
Console.WriteLine("\n\n Press any key to quite");
Console.Read();
}
}
}

Now I will explain a couple of code.

cmd.CommandText = "SELECT Count(*) FROM simplesql";

What we do here is count all the rows from simplesql.This must be done to know how long our for loop will be.

cmd.CommandText = "SELECT simple_id, simple_text FROM simplesql ORDER BY simple_id";

What we do here is select simle_id and simple_text from simplesql and order it by simple_id that means like 1, 2, 3,...
if you use ORDER BY simple_id DESC it will order reversed like ..., 3, 2, 1
Again you could choose to do it like this.
"SELECT * FROM simplesql"
This will make the query shorter but the gives you fewer control.
So if we only want to select the text we could do this.
"SELECT simple_text FROM simplesql ORDER BY simple_id"
Or if we want to select text where id equals 3 we would do this.
"SELECT simple_text FROM simplesql WHERE simple_id=3"
There is one more I want to teach you and that is if you
want to select text between some id numbers you will use this.
"SELECT simple_text FROM simplesql BETWEEN simple_id=0 AND simpel_id=5"
This would be usefully if you have a news system and want to show the last
5 news items this is the way

dr.Read();
Console.WriteLine("ID: {0} \t Text: {1}", dr[0], dr[1]);

Read one row from the database
dr[0] means the first variable you selected so
if you had the query like this: "SELECT simple_text, simple_id ..."
simple_text was dr[0]
But now simple_id is.

Summary

As you can see from this article, it is a very basic SQL article. In this article, I wasn't expecting you to know any SQL. I tried to keep this article very simple. I will be back with more articles on SQL with more SQL queries.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Jay Smith
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved