MySql 在 VB.net 中执行 Set 和 Concat 语句

标签 mysql sql vb.net datagridview

我正在尝试从 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命令执行。

我试图将代码拆分成单独的字符串,但出现了同样的错误。还尝试增加 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 中却需要大量代码。

最佳答案

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

关于MySql 在 VB.net 中执行 Set 和 Concat 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19426271/

相关文章:

vb.net - 每种颜色的 25 种颜色渐变

vb.net - 如何在 For Each...Next 循环中获取对象的索引?

mysql - 使用 UNION ALL 添加任意元组时的性能损失

mysql:计算子表中的记录,按日期分组

php - SQL查询显示当前时间之前的小时

sql - 如何从 DB2 中的列中获取表名?

php - 更新行时索引原因及错误

sql - 操作错误: near ",": syntax error - SQLITE3

MySQL逻辑计数操作

.net - 在 VB.NET 中确定文件大小