因此,@whatever 在 SQL 命令字符串中的存在给了我一个致命错误(在命令执行期间遇到了致命错误。)但当我在 MySQL 查询浏览器中执行相同的查询时却没有。
这是一个简单的示例,我为表中的每个 John 提供了一个行号,并在 datagridview 中显示它们:
private void button1_Click(object sender, EventArgs e)
{
_dataTable.Clear();
try
{
_conn = new MySqlConnection(Cs);
_conn.Open();
string name = "john";
//This is the string that gives me an error
string ConnString = "SELECT name,lastname,(@Row := @Row + 1) AS RowNumber FROM person JOIN (SELECT @Row := 0) r WHERE name = '"+name+"'";
//This one doesn't gives an error
//string ConnString = "SELECT name,lastname FROM person WHERE name = '" + name + "'";
_cmd = new MySqlCommand
{
Connection = _conn,
CommandText = ConnString
};
_cmd.ExecuteNonQuery();
_da = new MySqlDataAdapter(_cmd);
_da.Fill(_dataTable);
_cb = new MySqlCommandBuilder(_da);
dataGridView1.DataSource = _dataTable;
dataGridView1.DataMember = _dataTable.TableName;
dataGridView1.AutoResizeColumns();
_conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (_conn != null) _conn.Close();
}
}
为什么会发生这种情况,我该如何解决?我已经看到了很多关于此的问题,但没有具体的答案。