简体   繁体   English

C#在mysql查询参数中转义表名称中的字符

[英]C# Escaping characters in parameters on mysql query for table name

I'm making a simple mysql client to send some data. 我正在做一个简单的mysql客户端来发送一些数据。 I need my tables to have the date as a name in this format: 2014-07-04 我需要在表格中以以下格式将日期作为名称:2014-07-04

I know I have to wrap them around backticks(`) because of the (-). 我知道我必须将它们包装在反引号(`)周围,因为(-)。 Here's my code: 这是我的代码:

    public bool Update()
    {
        try
        {                
            MySqlCommand cmd = connection.CreateCommand();
            cmd.Parameters.AddWithValue("@TbName", "");
            foreach (Employee emp in this.employees)
            {
                foreach(shift singleShift in emp.shifts) 
                {
                    cmd.CommandText = "CREATE TABLE IF NOT EXISTS @TbName (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(40), aStart VARCHAR(5), aStop VARCHAR(5), Lunch VARCHAR(5), B1 VARCHAR(5), B2 VARCHAR(5), B3 VARCHAR(5));";                                                                    
                    cmd.Parameters["@TbName"].Value = singleShift.aDate; // singleShift.aDat = 2014-07-24                       
                    cmd.ExecuteNonQuery();            
                }
            }
        }
        catch (Exception ex)
        {
            return false;
        }
            return true;
    }

If I use this code, I get this error: 如果使用此代码,则会出现此错误:

 You have an error in your SQL syntax; check the manual that corresponds to your MySQL       server version for the right syntax to use near ''2014-06-29' (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(40), aSta' at line 1

So I've tried with a few methods to solve this like using "`" to concatenate the parameter but I get this error: 因此,我尝试了几种方法来解决此问题,例如使用“`”连接参数,但出现此错误:

 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''\`2014-06-29\`' (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(40), ' at line 1

and using MySqlHelper.EscapeString I get this error: 并使用MySqlHelper.EscapeString我收到此错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''\\\`2014-06-29\\\`' (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(40), ' at line 1

I know my tables should be named otherwise, but it is not possible in the current context. 我知道我的表应该以其他方式命名,但是在当前上下文中是不可能的。 What can I do to solve this? 我该怎么解决?

create a table with date name 用日期名称创建一个表

No, you can't use date as table name especially with -. 不,您不能将日期用作表名,尤其是-。 Change to something else. 改成其他东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM