通过C#在SQL-Server中准备语句

时间:2011-04-26 05:13:06

标签: c# php sql-server prepared-statement sqlcommand

我发现mysqli_stmt_prepare()函数在PHP中使用了预处理语句。 C#中的SQL-Server是什么样的? 我找到了这个代码示例(使用参数化命令)。这就是我要找的东西吗?

        SqlConnection conn = new SqlConnection();
        SqlCommand com = new SqlCommand();
        SqlDataAdapter dap = new SqlDataAdapter();
        DataTable tbl = new DataTable();
        SqlParameter param = new SqlParameter();
        conn.ConnectionString = @"Data Source=...";
        com.Connection = conn;
        com.CommandText = "select * from tbl1 where id<@id";
        com.Parameters.AddWithValue("@id",4);
        com.CommandType = CommandType.Text;
        dap.SelectCommand = com;
        conn.Open();
        dap.Fill(tbl);
        conn.Close();
        dataGridView1.DataSource = tbl;

如果不是那么什么? 如果是,请告诉我如何使用字符'?'而不是在命令文本中写@id 感谢

2 个答案:

答案 0 :(得分:2)

SQL Server(至少通过SqlClient)使用命名参数。该代码确实会执行参数化查询,但需要注意几点:

  • 它尚未正式“准备好”(见.Prepare()),但你几乎不需要反正
  • 其中一些对象是IDisposable;你应该为他们using
  • DataTable(以及适配器等)将工作,但处于拒绝状态(首选的地图类,IMO)
  • 在同一方法中看到DataGridViewSqlCommand可能意味着您的UI代码太靠近数据访问代码;我个人会将数据访问内容推到一个水平

例如:

DataTable tbl = new DataTable();
using(var conn = new SqlConnection(@"Data Source=..."))
using(var com = conn.CreateCommand())
{
    com.CommandText = "select * from tbl1 where id<@id";
    com.Parameters.AddWithValue("@id",4);
    com.CommandType = CommandType.Text;        

    SqlDataAdapter dap = new SqlDataAdapter();   
    dap.SelectCommand = com;
    conn.Open();
    dap.Fill(tbl);
    conn.Close();     
}
return tbl;

(并将其绑定到UI上的DataGridView

当然,如果参数值始终为4,您可以直接将其编码到TSQL中。

答案 1 :(得分:-1)

是的,但是无法使用'?'标记

相关问题