Using Command.Prepare with a SELECT, do I need to specify the SELECT columns as output parameters?
I'm trying to use Command.Prepare
with a CommandType.Text
query that has a single input parameter. The SELECT has several columns that I am extracting with a DataReader. Do I need to specify each of the select columns as output parameters before calling Command.Prepare()
? Even if I don't need to specify them, will performance improve if I do?
Example code:
using(var connection = new SqlConnection("connection string")
{
connection.Open();
using(var cmd = new SqlCommand(null, Connection))开发者_JAVA技巧
{
cmd.CommandText = "SELECT COLUMN1, COLUMN2, COLUMN3 " +
"FROM TABLE1 WHERE COLUMN4 = @thing";
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "@thing",
DbType = SqlDbType.Int,
Value = 1
});
//should I add output parms for COLUMN1, COLUMN2, COLUMN3?
cmd.Prepare();
using(var reader = cmd.ExecuteReader())
{
//get stuff out of reader
}
}
}
No, you don't need output parameters. You just get the results out of the reader in the normal way.
In fact, having the columns as output parameters wouldn't make sense, as you'll have a value per column per row rather than just one value for the whole call.
Linq's DataContext
provides a much easier way to use parameters than SqlCommand
:
class MyRow { public string Name { get; set; } }
class Program
{
static void Main(string[] args)
{
var dataContext = new System.Data.Linq.DataContext(
"Data Source=localhost\\sqlexpress;" +
"Initial Catalog=testdb;Integrated Security=SSPI;");
var rows = dataContext.ExecuteQuery<MyRow>(
"select * from testtable where name = {0}",
"Joe");
foreach (var r in rows)
Console.WriteLine(r.Name);
}
}
Although the syntax looks like string.Format
, the {0}
passed to ExecuteQuery
ends up being a real SQL parameter.
精彩评论