【问题标题】:How to add parameters to SQL when using使用时如何给SQL添加参数
【发布时间】:2014-09-30 05:32:50
【问题描述】:

鉴于此 C# 代码片段,我如何在 SQL 查询中使用 C# 变量?我知道最好的方法是使用“参数”,我已经看过很多例子,但到目前为止我还不能“把它放在一起”。

   ...
using MySql.Data.MySqlClient;

       public partial class Form1 : Form
        {
            private string server;
            private string database;
            private string uid;
            private string password;
            private MySqlConnection connection;

            public Form1()
            { 
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {

                webBrowser1.Navigate("127.0.0.1/box3.php");

                server = "localhost";
                database = "realestate_db";
                uid = "root";
                password = "";
                string connectionString;
                connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

                connection = new MySqlConnection(connectionString);
                connection.Open();
                MySqlDataAdapter mySqlDataAdapter;
                mySqlDataAdapter = new MySqlDataAdapter("SELECT `ID`, `lat` , `long` FROM `house` ", connection); // want to uses a C# variable in this SQL query

                DataSet DS = new DataSet();
                mySqlDataAdapter.Fill(DS);
                dataGridView1.DataSource = DS.Tables[0];

            }
     ....       

Thanks.

【问题讨论】:

  • 你现在的代码有什么问题?错误信息?意外行为?
  • @eddie_cat 代码不完整。他想知道如何扩展以在 sql 字符串的 where 子句中包含类似过滤器的内容,而不会让自己对 sql 注入开放。
  • 哎呀,看了一眼,我以为他已经在尝试参数化,只是在让他的代码工作时遇到问题。没看到评论。
  • @Bearcat9425 我同意这可能是重复的,但让我们找到一个不同的问题作为原始问题使用。 AddWithValue() 方法不是你的朋友。

标签: c# mysql


【解决方案1】:

这是一个非常常见的问题的重复,我正在使用另一篇文章描述的代码复制和粘贴,链接在这里Creating and then working with parameters in queries。您可以在 dataadapter Select 命令中使用 addWithValue 方法,也可以使用 add 方法。

da = new MySqlDataAdapter("SELECT `ID`, `lat` , `long` FROM `house` where `ID` = ?ID", connection);
// As most are suggesting Create the parameters with the Add Method, Passing the MySqlDbType  
da.SelectCommand.Parameters.Add("?ID",MySqlDbType.Int32).Value = ID;
 // Can also Use AddWithValue Method as well  
da.SelectCommand.Parameters.AddWithValue("?ID",<Your Variable>);

【讨论】:

  • 如果经常被问到你应该把它标记为重复,这里不要回答
  • 你也在回答 Sql 而不是 MySql
  • MySql 使用 ?'s- 请参阅下面的答案
  • 实际上这是错误的,我有工作代码,@ sysmbol 工作得很好。
  • 很高兴知道——奇怪的是 MySql 文档并没有说你可以使用它——但如果它有效,那就这样吧。
【解决方案2】:

来自MySqlDataAdapter

  public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn)
  {
    MySqlDataAdapter da = new MySqlDataAdapter();
    MySqlCommand cmd;
    MySqlParameter parm;
    // Create the SelectCommand.
    cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=?id AND name=?name", conn);
    cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15);
    cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15);
    da.SelectCommand = cmd;
    // Create the InsertCommand.
    cmd = new MySqlCommand("INSERT INTO mytable (id,name) VALUES (?id,?name)", conn);
    cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15, "id" );
    cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15, "name" );

    da.InsertCommand = cmd;  
    return da;
  }

【讨论】:

    【解决方案3】:

    首先,将所有数据访问抽象到它自己的类或程序集中:

    public class DAL
    {
    
        private string server = "localhost";
        private string database = "realestate_db";
        private string uid = "root";
        private string password = "";
        private string connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
    
        public DataSet GetHouse(int ID) 
        {
            //...
        }
    }
    

    那么你现有的代码会调用这个方法:

    public DataSet GetHouse(int ID)
    {
        string sql = "SELECT `ID`, `lat` , `long` FROM `house` WHERE ID= ?ID ";
        DataSet result = new DataSet();
    
        using (var cn = new MySqlConnection(connectionString) )
        using (var cmd = new MySqlCommand(sql, cn) )
        using (var da = new MySqlDataAdapter(cmd) )
        {
           cmd.Parameters.Add("?ID", MySqlDbType.Int32).Value = ID;
    
           da.Fill(result);
        }
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      相关资源
      最近更新 更多