I need to execute a sql query from within a c# class. I have thought of 2 options
My question is which would be the better way? It's important that the solution only holds a connection to the server for a short time.
I'm open to other ideas if the above aren't good.
Thanks in advance.
C is an alias for the results from the sub-query (select min(A. bidvalue) as ....). This subquery will product a result set which behaves like a table for the duration of the query. To refer to this result set and its columns, it was given the alias name "C" and all C.
You can code SQL statements in a C or C++ program wherever you can use executable statements. Each SQL statement in a C or C++ program must begin with EXEC SQL and end with a semicolon (;). The EXEC and SQL keywords must appear on one line, but the remainder of the statement can appear on subsequent lines.
C is about performing actions. SQL is about storing data, and manipulating data. The only "actions" it is good at are pulling and changing data. Think of all your data like a Venn diagram- SQL lets you "look" at any part of that diagram you want.
The tables in the following sections provide a functional summary of SQL statements and are divided into these categories: Data Definition Language (DDL) Statements. Data Manipulation Language (DML) Statements.
Use a SqlCommand. This code will only keep the connection alive for a very short period of time (as long as your query is performant):
DataTable results = new DataTable();
using(SqlConnection conn = new SqlConnection(connString))
using(SqlCommand command = new SqlCommand(query, conn))
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
dataAdapter.Fill(results);
From MSDN:
The following example creates a SqlConnection, a SqlCommand, and a SqlDataReader. The example reads through the data, writing it to the console. Finally, the example closes the SqlDataReader and then the SqlConnection as it exits the Using code blocks.
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With