CyberArmy University | Open Source Institute | CyberArmy Intelligence & Security | CyberArmy Services & Projects

[Library Index]

[View category: Programming] [Discuss Article]

Writing your own SQL Query Analyser in C#

Article is yet to be rated
Author:      Prothis
Submitted:      04-Apr-2004 08:52:03
Imported From:      zZine (original author: Sorcer)


How to write a Windows form in the C# .Net programming language which takes a SQL instruction and dynamically produces a results list in about 7 lines of code.
How to write a Windows form in the C# .Net programming language which takes a SQL instruction and dynamically produces a results list in about 7 lines of code.

1) Get a .NET IDE such as VS.NET or SharpDevelop free (google for it)

2) Create a new C# Windows Forms project

3) Add a textbox and button to the top of the form for accepting user input. Set the textbox to be multiline and set the text of the button to 'Execute'

4) Use the Server Explorer to navigate to you database. Highlight the database and drag it onto your workspace (this creates sqlConnection1 binding to the database).

5) Open the Windows forms toolbox and drag a datagrid onto your workspace. This is where the results will be displayed. Align it nicely at the bottom of the form.

6) Double click the Execute button to go to the click event and enter the following code:
private void button1_Click(object sender, System.EventArgs e) 
{ //create a new sql command object of type dynamic sql 

SqlCommand cmd = sqlConnection1.CreateCommand(); 

cmd.CommandType = CommandType.Text;  

//set the sql command to whatever is in the textbox 

cmd.CommandText = textBox1.Text; 

//create a new data adapter and bind it to the command object 

SqlDataAdapter da = new SqlDataAdapter(); 

da.SelectCommand = cmd; 

//create a new dataset and fill it with results based adapter 

DataSet ds = new DataSet(); 

da.Fill(ds, "Results"); 

//bind the local variable dataset to the datagrid on the form 

dataGrid1.DataSource = ds; 

dataGrid1.DataMember = "Results"; 
} 
7) Make sure you have a main method which starts your form (mine is called SQLForm).
static void Main() 
{ 
Application.Run(new SQLForm()); 
} 
8) Run your project, input a valid sql statement and watch those dynamic results come flooding back. You can call any statement, including executing stored procedures.

Prothis

This article was originally published by CyberArmy.net in the CyberArmy Library.

You must be logged in to vote on an article

About Us | Privacy Policy | Mission Statement | Help