Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to directly execute SQL query in C#?

Ok, I have an old batch file that does exactly what I need. However, with out new administration we can't run the batch file anymore so I need to start up with C#.

I'm using Visual Studio C# and already have the forms set up for the application I need to build. (I'm learning as I go)

Here is what I need to accomplish in C# (This is the batch guts)

sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS  -s ; -W -w 100 -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '%name%' " 

Basically it uses SQLCMD.exe with the already existing datasource called PDATA_SQLExpress.
I've searched and gotten close but I'm still at a loss on where to start.

like image 484
Redracer68 Avatar asked Feb 11 '14 17:02

Redracer68


People also ask

Can we use SQL in C language?

You can code SQL statements in a C or C++ program wherever you can use executable statements. Each SQL statement in a C or C++ program must begin with EXEC SQL and end with a semicolon (;). The EXEC and SQL keywords must appear on one line, but the remainder of the statement can appear on subsequent lines.

How do I execute a SQL query?

Running a SQL CommandEnter the SQL command you want to run in the command editor. Click Run (Ctrl+Enter) to execute the command. Tip: To execute a specific statement, select the statement you want to run and click Run.

How can I directly execute SQL queries in LINQ?

Add a LINQ to SQL class file. Drag and drop the respective table. Now, copy this code in the main method. We are creating an instance of sample datacontext class and then we are using this ExecuteQuery method to execute the SQL query.


1 Answers

To execute your command directly from within C#, you would use the SqlCommand class.

Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:

string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName"; string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";  using (SqlConnection connection = new SqlConnection(connectionString)) {     SqlCommand command = new SqlCommand(queryString, connection);     command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");     connection.Open();     SqlDataReader reader = command.ExecuteReader();     try     {         while (reader.Read())         {             Console.WriteLine(String.Format("{0}, {1}",             reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc         }     }     finally     {         // Always call Close when done reading.         reader.Close();     } } 
like image 100
Nate Avatar answered Sep 30 '22 14:09

Nate