MySqlCommand.ExecuteNonQuery错误和奇怪的c#

时间:2011-11-13 08:36:28

标签: c# executenonquery

我尝试将路径名插入到mysql数据库中,但它的工作却很奇怪。我找到的是路径不是我的项目目录的路径它奇怪的东西。当我使用我的程序时,结果是“ D:musicFOREIGN !! New folderarat cakepHilary Duff - Wake Up.mp3 ”。 当我从phpmyadmin手动插入查询时,其结果为“ D:\ music \ FOREIGN !! \ New folder \ barat cakep \ Hilary Duff - Wake Up.mp3 ”,没什么奇怪的。我做错了什么?这是我的代码:

public static void add_song(song input)
    {
        establised();
        try
        {
            MySqlCommand command = connection.CreateCommand();
            command.CommandText = string.Format("INSERT INTO song (ID_SONG, ID_GENRE, ID_CATEGORY, SONG_TITLE, SONG_ARTIST, SONG_LOCATION, SONG_PLAYED) select '', b.id_genre, c.id_category, '{0}', '{1}', '{2}', '0' from genre b, category c where b.genre = '{3}' and c.category = '{4}' ", input.title, input.artist, input.location, input.genre, input.category);
            command.ExecuteNonQuery();
        }
        catch (Exception e) { }
        release();
    }

这是我的示例查询:

"INSERT INTO song (ID_SONG, ID_GENRE, ID_CATEGORY, SONG_TITLE, SONG_ARTIST, SONG_LOCATION, SONG_PLAYED) select '', b.id_genre, c.id_category, 'Wake Up', 'Hilary Duff', 'D:\\music\\FOREIGN!!\\New folder\\barat cakep\\Hilary Duff - Wake Up.mp3', '0' from genre b, category c where b.genre = 'Pop' and c.category = 'international'"

2 个答案:

答案 0 :(得分:3)

使用MysqlParameter对象将参数传递给查询,因此会自动检查:

// 1. Use parameters label in the query
command.CommandText = "INSERT INTO song (ID_SONG, ID_GENRE, ID_CATEGORY, SONG_TITLE, SONG_ARTIST, SONG_LOCATION, SONG_PLAYED) select '', b.id_genre, c.id_category, @Title, @Artist, @Location, '0' from genre b, category c where b.genre = @GenRe and c.category = @category "

// 2. Define parameters used in command object
    MySqlParameter param  = new MySqlParameter();
    param.ParameterName = "@Location";
    param.Value         = input.location;

//3. Assign the parameter to the command
command.Parameters.Add(param);

//GO ahead with others parameters ...

答案 1 :(得分:0)

您只需要转义查询字符串中的任何文本变量。

需要转义的两个字符是撇号(')和斜杠(\)。

创建一个简单的“FixSQL”函数

Public Shared Function FixSQL(item As String) As String
    Dim result As String

    result = item
    result = Replace(result, "\", "\\")
    result = Replace(result, "'", "''")
    return result
End Function

仅将函数应用于sql查询中的变量