使用C#在TextBox中准备语句查询

时间:2023-01-12 00:06:44

I'm using Visual Studio 2013 and doing this for my personal project. What I am trying to do is that I tried to use prepared statement in this query however I still get @fname eventhough I typed first name in textbox. Do you know what is wrong? Sorry, my English is difficult for me but I'm doing my best to explain this.

我正在使用Visual Studio 2013并为我的个人项目执行此操作。我想要做的是我尝试在这个查询中使用预处理语句但是我仍然得到@fname,尽管我在文本框中输入了第一个名字。你知道什么是错的吗?对不起,我的英语对我来说很难,但我正在尽力解释这一点。

query = "SELECT pkey.keyword AS \"Keyword\", p.title AS \" Title\", p.abstract AS \"Abstract\", p.citation AS \"Citation\", CONCAT_WS(\" \", f.fname, f.lname) AS \"Name\", f.email AS \"Email\" " +
  " FROM paper_keywords pkey" +
  " INNER JOIN papers p ON pkey.id = p.id" +
  " INNER JOIN authorship a ON p.id = a.paperId" +
  " INNER JOIN faculty f ON a.facultyId = f.id WHERE " +
  " f.fname LIKE \"%@fname%\" ";

Here is my codes at below:

以下是我的代码:

conn = new MySqlConnection(stringConn);
cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@fname", fnametextBox.Text);
conn.Open();

DataTable datatable = new DataTable();
adapter = new MySqlDataAdapter(cmd);
adapter.Fill(datatable);

dataGridView1.DataSource = datatable;
dataGridView1.DataBindings.ToString();
MessageBox.Show(query);

1 个解决方案

#1


If I understand correctly, you are wondering why, when you output your query into a messagebox, you still see @fname in the query? If that is so: the query you write with a named sql parameter will stay the same, and will not be substituted by the value you put into the textbox, it is the database that will replace the parameter with your value, so your query will always contain @parameterName, but in the database engine it will use the value of your variable.

如果我理解正确,您想知道为什么当您将查询输出到消息框中时,您仍然在查询中看到@fname?如果是这样的话:使用命名的sql参数编写的查询将保持不变,并且不会被放入文本框的值替换,它是用您的值替换参数的数据库,因此您的查询将始终包含@parameterName,但在数据库引擎中它将使用变量的值。

#1


If I understand correctly, you are wondering why, when you output your query into a messagebox, you still see @fname in the query? If that is so: the query you write with a named sql parameter will stay the same, and will not be substituted by the value you put into the textbox, it is the database that will replace the parameter with your value, so your query will always contain @parameterName, but in the database engine it will use the value of your variable.

如果我理解正确,您想知道为什么当您将查询输出到消息框中时,您仍然在查询中看到@fname?如果是这样的话:使用命名的sql参数编写的查询将保持不变,并且不会被放入文本框的值替换,它是用您的值替换参数的数据库,因此您的查询将始终包含@parameterName,但在数据库引擎中它将使用变量的值。