c# - 使用时如何给SQL添加参数

标签 c# mysql

给定此 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.

最佳答案

这是一个非常常见的问题的重复,我正在使用从另一篇描述的文章复制和粘贴的代码,链接在这里 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>);

关于c# - 使用时如何给SQL添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26108291/

相关文章:

c# - 是否有任何预先存在的可枚举扩展使其 NullReferenceException 安全?

c# - 内容占位符背景图片

php - 新闻门户和数据库的重量

php - 使用 NodeJS 使用数据库进行实时实时更新 View

c# - 根据实体类型覆盖 EF 6 中的默认 SQL 生成

c# - WPF FontFamily格式问题

c# - 使用 Windows C# 第三方程序更改 IOS 应用程序名称

MySQL将ip地址从varchar列复制到同一个表中的整数

mysql - 如何解决mysql警告: "InnoDB: page_cleaner: 1000ms intended loop took XXX ms. The settings might not be optimal "?

mysql - 从 MySQL 表中选择随机查询