2011-11-13 32 views
-1

我嘗試將路徑名插入到mysql數據庫,但它的工作卻奇怪。我發現的是路徑不是我的項目目錄的路徑奇怪。當我使用我的程序時,結果是「D:musicFOREIGN !! New folderarat cakepHilary Duff - Wake Up.mp3」。 當我從phpmyadmin手動插入查詢時,其結果爲「D:\ music \ FOREIGN !! \ New folder \ barat cakep \ Hilary Duff - Wake Up.mp3」,沒什麼奇怪的。我做錯了什麼?這裏是我的代碼:MySqlCommand.ExecuteNonQuery錯誤和奇怪的c#

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'" 

回答

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 ... 
+0

OKE的變量。我會試試..^_^ –

+0

其作品.. !!!^_^ 非常感謝你.. –

+1

如果答案解決了你的問題,你可以考慮接受它;) – aleroot

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查詢