1

我正在尝试从 MySQL 获取一些值 - 列作为行,反之亦然 - 以显示在DataGridView. 我有这段代码,应该在 MySQL 中运行-

SET @header = CONCAT('SELECT \'sl\', ',
    (SELECT GROUP_CONCAT(CONCAT(' \'', sl, '\'')) FROM cars where sl=1),
    ' LIMIT 0, 0');

SET @a = -1;
SET @line1 = CONCAT(
    'SELECT \'Plate\',',
    (
        SELECT GROUP_CONCAT(
            CONCAT(' (SELECT Plate FROM cars LIMIT ',
                @a:=@a+1,
                ', 1)')
            )
        FROM cars where sl=1
    ));

SET @a := -1;
SET @line2 = CONCAT(
    'SELECT \'Brand\',',
    (
        SELECT GROUP_CONCAT(
            CONCAT(' (SELECT Brand FROM cars LIMIT ',
                @a:=@a+1,
                ', 1)')
            )
        FROM cars where sl=1
    ));

SET @query = CONCAT('(',
    @header,
    ') UNION (',
    @line1,
    ') UNION (',
    @line2,
    ')'
);

PREPARE my_query FROM @query;
EXECUTE my_query;

现在,当我尝试通过ExecuteNonQuery将所有这些代码保存在一个字符串中来通过命令运行它时,我得到一个MySQLException错误-Fatal error encountered during command execution.

我试图将代码拆分为单独的字符串,但弹出相同的错误。也试图增加CommandTimeout,但没有任何效果。

有什么特殊的方法可以运行这些语句吗?还是代码有问题?请注意,这在命令行客户端上有效运行,没有任何错误。

PS:代码来自 Q# 3288014 - 感谢 Anax

编辑:

我找到了解决同一件事的方法,但都是在 VB 中完成的。

Dim sa() As String = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Dim sa2() As String = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
connect()
Dim reader As MySqlDataReader
execstr = "describe cars"
Dim cmd As New MySqlCommand(execstr, connection)
reader = cmd.ExecuteReader()
Dim i As Integer = 0
While reader.Read
    sa(i) = reader.GetString(0)
    i = i + 1
End While
reader.Close()
connection.Close()
connect()
execstr = "select*from cars where sl=1;"
Dim cmd2 As New MySqlCommand(execstr, connection)
reader = cmd2.ExecuteReader()
While reader.Read
   For i1 As Integer = 0 To sa.Length - 1
        sa2(i1) = reader.GetString(i1)
   Next
End While
reader.Close()
connection.Close()
reader.Close()
connection.Close()
Dim t As New DataTable
t.Columns.Add(sa(0))
t.Columns.Add(sa2(0))
For y As Integer = 1 To sa.Length - 1
    t.Rows.Add(sa(y), sa2(y))
Next
DataGridView1.DataSource = t

有趣的是,在 MySQL 中所有可以在字符串中完成的事情,在 VB 中需要这么多代码。

4

1 回答 1

0

您不能在单个或一系列ExecuteNonQuery命令中执行此操作。此示例显示了您将在 mysql 上的存储过程中放入的代码。您使用 DataAdapter 或 DataReader 调用存储过程。

于 2013-10-17T15:04:53.683 回答