Certainly! Executing a SQL query in ADO.NET involves creating a SqlCommand object and executing it against a SqlConnection. Here's a basic example demonstrating how to execute a SQL query in a SQL Server database using ADO.NET:
Example
using System;
using System.Data;
using System.Data.SqlClient;
namespace YourNamespace
{
public class YourClassName
{
public void ExecuteQuery()
{
// Connection string to your database
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourUsername;Password=YourPassword";
// SQL query to execute
string query = "SELECT * FROM YourTable";
// Create a SqlConnection to connect to the database
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create a SqlCommand to execute the query
using (SqlCommand command = new SqlCommand(query, connection))
{
try
{
// Open the database connection
connection.Open();
// Execute the SELECT query
SqlDataReader reader = command.ExecuteReader();
// Check if the SqlDataReader has rows
if (reader.HasRows)
{
// Loop through the rows and display data
while (reader.Read())
{
int id = reader.GetInt32(reader.GetOrdinal("ID"));
string name = reader.GetString(reader.GetOrdinal("Name"));
int age = reader.GetInt32(reader.GetOrdinal("Age"));
Console.WriteLine($"ID: {id}, Name: {name}, Age: {age}");
}
}
else
{
Console.WriteLine("No data found.");
}
// Close the SqlDataReader
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
}
}
}
In this example:
ExecuteQuery
to execute the SQL query.SqlConnection
to connect to the database using a connection string.SqlCommand
with the SQL query and a SqlDataReader
to read the results.ExecuteReader()
method of the SqlCommand
.You can call this ExecuteQuery
method from your ASP.NET code-behind or controller to execute the SQL query. Make sure to replace placeholders like YourServer
, YourDatabase
, YourUsername
, YourPassword
, YourTable
with the actual values relevant to your database setup.