Listen
using System; using System.Data.SqlClient; class Program { static void Main(string[] args) { string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "SELECT * FROM Customers"; using (SqlCommand command = new SqlCommand(sql, connection)) { SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["CustomerName"] + " - " + reader["ContactName"]); } reader.Close(); } connection.Close(); } } }This example connects to a SQL Server database using a connection string, executes a
SELECT
query to retrieve data from theCustomers
table, iterates over the result set using awhile
loop, and outputs the customer names and contact names to the console. The following steps are performed:
- Define a connection string variable
connectionString
with the appropriate values for the server address, database name, username, and password.- Use the
SqlConnection
class to create a new connection object and open the connection using theOpen()
method.- Define a SQL query string
sql
that selects all columns from theCustomers
table.- Use the
SqlCommand
class to create a new command object with thesql
query string and the open connection.- Use the
ExecuteReader()
method of the command object to execute the query and retrieve aSqlDataReader
object.- Use a
while
loop to iterate over the rows in the result set using theRead()
method of theSqlDataReader
object.- Output the values of the
CustomerName
andContactName
columns from each row to the console usingConsole.WriteLine()
.- Close the
SqlDataReader
object using theClose()
method.- Close the connection using the
Close()
method of the connection object.Note that there are many other database-related concepts and operations you can perform, such as inserting, updating, and deleting records, as well as working with other database management systems such as MySQL, Oracle, and MongoDB. This example is just one possible multi-step process for working with databases.