无法识别 MySql 查询中的 C# 变量

标签 c# mysql sql visual-studio-2017 query-string

我的 C# 代码中有一个 int 变量,我正在尝试在 MySql 查询中使用它。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace projeV1
{

    public partial class ProjeDetay : Form
    {

        public ProjeDetay()
        {
            InitializeComponent();
        }

        private void ProjeDetay_Load(object sender, EventArgs e)
        {

            int satir_projem = Projeler.satir_proje;
            string connectionString = "Server = localhost; Port = ...; Database = ...; Uid = root; Pwd = ...; Allow User Variables=True";
            MySqlConnection databaseConnection = new MySqlConnection(connectionString);
            MySqlCommand command;

            databaseConnection.Open();
            command = databaseConnection.CreateCommand();

            string myQuery = "select projeAdi from projeler where projeID = @satir_projem";
            MySqlDataAdapter dataAdapter = new MySqlDataAdapter(myQuery, databaseConnection);
            command.Parameters.Add("@satir_projem", MySqlDbType.Int32).Value = satir_projem;

            DataSet DS = new DataSet();
            dataAdapter.Fill(DS);
            dataGridView_ProjeDetay.DataSource = DS.Tables[0];

            MessageBox.Show(Projeler.satir_proje.ToString());

            MessageBox.Show(satir_projem.ToString());
        }
    }
}

(抱歉,如果编码方面看起来很困惑,但我是新手 ^^)

MessageBox 窗口正确显示变量值,因此变量没有问题。例如,当我将查询字符串中的@satir_projem替换为“2”之类的数字时(请参见下面的示例),结果是正确的,但是当我在查询中使用@satir_projem时,它不起作用。我看不出我做错了什么。

示例查询字符串:

"select projeAdi from projeler where projeID = 2"

P.S 1:最初,我试图获取 DataGridView 中所选行的索引(即名为 Projeler.satir_proje 的变量),该 DataGridView 用于名为“Projeler”的表单和另一种表单(名为 ProjeDetay) ,将该索引值分配给另一个名为“satir_projem”的变量,并使用该值从我的数据库获取相关数据,并将该数据放入第二个表单中的另一个 DataGridView(称为 dataGridView_ProjeDetay)中。

P.S 2:我对这个问题做了很多研究,并尝试了我一路上遇到的许多解决方案;然而,他们都不适合我。所以,我在这里:)

提前致谢。

最佳答案

您正在为未使用的命令设置参数。 相反,您应该使用 DataAdapter.SelectCommand

dataAdapter.SelectCommand.Parameters.Add(...)

关于无法识别 MySql 查询中的 C# 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53719930/

相关文章:

c# - 使用c#在mvc4中使用viewbag数据的下拉列表

MySQL仅对特定数量的记录进行分组(在JOIN表达式中查询)

php - 使用 PDO::bindValue(带或不带类型标识符)与执行之间有什么区别吗?

mysql - 简单 INDEX 查询的性能很糟糕

c# - EF核心: "The LINQ expression could not be translated" when using explicit casting

c# - 只读的属性,但只能在类之外

php num_rows 不工作

sql - 查找 PC 型号对

java - 尝试从 "JTable"获取值并将其设置为 "Jtextfield"

C# 在 Word 文档中查找和替换文本的替代方法