query sql database in csharp

To query a SQL database in C#, you can use the SqlConnection class to establish a connection to the database and the SqlCommand class to execute SQL statements.

Here is an example code snippet:

main.cs
using System.Data.SqlClient;

// Create a connection to the database
string connectionString = "server=myServerAddress;database=myDataBase;uid=myUsername;pwd=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);

// Open the connection
connection.Open();

// Create a SQL command
string sql = "SELECT FirstName, LastName FROM Customers";
SqlCommand command = new SqlCommand(sql, connection);

// Execute the command and read the results
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
    string firstName = reader.GetString(0);
    string lastName = reader.GetString(1);
    Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

// Close the connection and reader
reader.Close();
connection.Close();
754 chars
26 lines

This code establishes a connection to a database using a connection string, creates a SQL command to select data from a table, executes the command, and reads the results using a SqlDataReader. Finally, the connection and reader are closed.

gistlibby LogSnag