Introduction
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 going to SQL queries, we need to know how to connect to a database. I will use an 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 namespaces into my application before writing anything else.
using System.Data;
using System.Data.SqlClient;
Now let's create a connection object. The following code snippet creates a SqlConnection 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 Query in SQL
I want to show you that using SQL queries in your application is relatively easy. I will explain the CREATE, INSERT, and SELECT queries in this article.
Now if you wonder why 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 really 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 on the code so you can uneasily understand what's going on there.
The last thing we have to do is make a Primary key t. Thiss 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 used this query instead of ours, "CREATE DATABASE csharpcorner." "Use this instead of the create table query. You also need to change the connection string and delete this part from it "Initial Catalog=database_name;"+
INSERT Query in SQL
The INSERT SQL query is the second most used query. I think you have an idea of what it is for. Yes, it's for inserting data into a database table. You will see how the INSERT query works in a moment. The INSERT query works almost the same as the create a 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 into the database
And here is the code
G GPosted Feb 17, 2023, 8:01 AM
WARNING : Beware of SQL Injection using the code presented here as-is
raiden sakauPosted Jul 31, 2011, 11:48 PM
aaaaa
Apurva MehtaPosted Oct 11, 2010, 12:42 AM
In insert Query if the value of strtext is say abcd's then it will throw exception.How to solve this types of problem
Shahriar KhondokarPosted Jun 4, 2010, 2:58 AM
This is a very good article. Check this article HOW TO: SQL & C# for details on how to connect to SQL Server database from C#.NET database applications as well as Java database applications. It also describes how to pass embedded SQL queries (SELECT, INSERT, UPDATE, DELETE), calling stored procedures, pass parameters etc. Shahriar Nour Khondokar
williams rodrig constantinoPosted Jan 14, 2010, 1:41 AM
Felicidades williams rodriguez