Junior — Middle
Have you directly interacted with a database through queries?
sobes.tech AI
Answer from AI
Yes, interacting with a database through direct SQL queries is common practice, especially in the early stages of development or when precise control over queries is needed. In C#, this is often done using the SqlCommand class from the System.Data.SqlClient namespace.
Example of a simple database query:
using System.Data.SqlClient;
string connectionString = "Data Source=server;Initial Catalog=db;Integrated Security=True;";
string query = "SELECT * FROM Users WHERE Id = @id";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@id", 1);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["Name"].ToString());
}
}
}
This approach allows flexible query formation but requires careful handling of parameters to avoid SQL injection.