Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

ASP.NET ADO(ActiveX Data Objects for .NET) Query:


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:

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.


Advertisement
Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java