SQL C#

Reading with Parameters to Prevent SQL Injection

This C# program demonstrates how to read an SQL table with paraters to prevent SQL injection in a database for Microsoft SQL in C#.

Program.cs

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

namespace SqlQueries {
    class Program {
        static void Main(string[] args) {
            using (SqlConnection qConnection = new SqlConnection(@"Server=LAPTOP-FHJLCP14\SQLEXPRESS;Trusted_Connection=True;Database=XoaX;")) {
                string sApostleName = "Peter";
                qConnection.Open();

                Console.WriteLine("State = " + qConnection.State);
                Console.WriteLine(qConnection.ClientConnectionId);

                SqlCommand sqlCommand = new SqlCommand() {
                    CommandText = "SELECT * FROM Apostles WHERE name = @apostleName",
                    CommandType = CommandType.Text,
                    Connection = qConnection
                };
                // Parameterize to prevent SQL injection
                sqlCommand.Parameters.AddWithValue("@apostleName", sApostleName);

                using (SqlDataReader qSqlReader = sqlCommand.ExecuteReader()) {
                    while (qSqlReader.Read()) {
                        Object[] qaColumns = new Object[qSqlReader.FieldCount];
                        qSqlReader.GetValues(qaColumns);
                        // Read all of the entries in the row
                        foreach (object qEntry in qaColumns) {
                            Console.Write(qEntry + " | ");
                        }
                        Console.WriteLine();
                    }
                }
            }
        }
    }
}
 

Output

State = Open
0cc91a62-cb29-43db-82a6-ce0e8a864cba
Peter | Keys and cross | Simon | fisherman | 1 |
Press any key to continue . . .
 

Tables

Tables
 
 

© 2007–2025 XoaX.net LLC. All rights reserved.