c# - 无法识别 MySql 查询中的 C# 变量
问题描述
我的 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"
PS 1:最初我试图在 DataGridView 中获取所选行的索引(即名为 Projeler.satir_proje 的变量),该数据用于名为“Projeler”的形式和另一种形式(名为 ProjeDetay),分配将值索引到另一个名为“satir_projem”的变量中,并使用此值从我的数据库中获取相关数据,并将该数据放入位于我的第二种形式(称为 dataGridView_ProjeDetay)的另一个 DataGridView 中。
PS 2:我对这个问题做了很多研究,并尝试了很多我在此过程中遇到的解决方案;但是,它们都不适合我。所以,我在这里:)
提前致谢。
解决方案
您正在为未使用的命令设置参数。相反,您应该使用DataAdapter.SelectCommand
dataAdapter.SelectCommand.Parameters.Add(...)
推荐阅读
- powershell - 编写脚本,从 LastModificationDate 属性按月对文件进行排序
- java - 如何在java中找到5个整数的中位数
- django - Django_tables2 NonType 对象不可迭代
- android - 制作切割字符串android的算法
- visual-studio-code - 视觉工作室代码:在片段中展开片段
- jenkins - Jenkins 在 Jenkins 的不同节点上并行运行测试给了我在步骤中找不到这样的 DSL 方法“代理”
- google-sheets - 如何查看每一行的 ARRAYFORMULA SUMIF?
- python - 在 Mac 上安装 SIP for Python 2.7
- facebook - 在 Facebook Graph API 中指定日期时遇到问题
- r - 按字符值填充缺失数据