Path Stored in database is not right

c#, mysql, winforms

Solution

Perhaps MySQL thinks that the "\" character is an escape, so that's why it does not contain it in the string. Try

c.Replace(@"\", @"\\")

when you insert, so the escape character will be escaped.

EDIT: For example, replace the command text initializing line like this. Also add an escape for single quotes.

string escapedPath = c.Replace(@"\", @"\\").Replace("'", @"\'");    
command.CommandText = ("Insert into data (path) values('" + escapedPath + "')");

EDIT: See @Matthew's answer for an even more "best practice" solution, using parameterized queries.

Problem

``` private void button14_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string c = openFileDialog1.FileName; string connString = "Server=Localhost;Database=test;Uid=root;password=root;"; MySqlConnection conn = new MySqlConnection(connString); MySqlCommand command = conn.CreateCommand(); command.CommandText = ("Insert into data (path) values('" + c + "')"); conn.Open(); command.ExecuteNonQuery(); conn.Close(); MessageBox.Show("Success"); } } ``` This code works for me, but unfortunately, the path stored in database is not right .. the stored path is like this (`C:Users hesisDesktopREDEFENSEResourcesImagesRED1f.png`) where it supposed to be like this (`C:P/Users/thesis/Desktop..../1f.png`). But when I checked the "sr" value with this code.. the msgbox show just right.. ``` private void button14_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { MessageBox.Show(openFileDialog1.FileName); } } ``` why is it happening then?

Original source

Related problems