如何将mysql查询转换为可接受的c#字符串?

时间:2016-09-20 11:56:33

标签: c# mysql .net winforms

如果列不存在,我会动态地使用mysql创建列。我得到了在mysql控制台中运行的代码,但是当涉及到c#时,它给了我“在命令执行期间遇到的致命”

SET @preparedStatement = (SELECT IF(
(SELECT COUNT(*)
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE  table_name = 'tableName'
    AND table_schema = DATABASE()
    AND column_name = 'colName'
) > 0,
"SELECT 1",
"ALTER TABLE `tableName` ADD `colName` TINYINT(1) NULL DEFAULT '0';"
));

PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

上面的代码我转换为c#string为

string qry = "SET @preparedStatement = ( SELECT IF( (SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME = '" + tname + "' AND COLUMN_NAME = '" + code + "_C' ) > 0, \"SELECT 1', \"ALTER TABLE " + tname + " ADD " + code + "_C int(3) NOT NULL default '0'; \" )); PREPARE alterIfNotExists FROM @preparedStatement; EXECUTE alterIfNotExists; DEALLOCATE PREPARE alterIfNotExists;";

错误是什么?

执行代码:

    private void columnCreate_Load(object sender, EventArgs e)
    {
        string tname = "bca_i"; //for temprory
        string code = "BCAXX";//for temprory
        string qry = @"SET @preparedStatement = ( SELECT IF( (SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME = '" + tname + "' AND COLUMN_NAME = '" + code + "_C' ) > 0, \"SELECT 1', \"ALTER TABLE " + tname + " ADD " + code + "_C int(3) NOT NULL default '0'; \" )); PREPARE alterIfNotExists FROM @preparedStatement; EXECUTE alterIfNotExists; DEALLOCATE PREPARE alterIfNotExists;";
        try
        {
            using (MySqlConnection conn = new MySqlConnection(ConStr))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(qry, conn))
                {
                    cmd.ExecuteNonQuery();
                }

            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

2 个答案:

答案 0 :(得分:0)

部分

\"SELECT 1', \"A

中的原始查询不符
"SELECT 1",
"A
你发现了吗?您将"替换为1后的'

答案 1 :(得分:0)

我只想知道检查列存在的其他方法..只是使用下面的查询并检查列是否存在迭代遍历列的循环

string last_col = "SELECT COLUMN_NAME FROM information_schema.COLUMNS  WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME ='" + subCodeText.Text + "'";

其中attendance是数据库,subCodeText.Text是我的表名。