C# 数据库中存储的路径不正确
这段代码适合我,但不幸的是,数据库中存储的路径不正确。。存储的路径如下(C# 数据库中存储的路径不正确,c#,mysql,winforms,C#,Mysql,Winforms,这段代码适合我,但不幸的是,数据库中存储的路径不正确。。存储的路径如下(C:Users hesisdesktopredefenseresourceismagesred1f.png),其中应该是这样的(C:P/Users/thesis/Desktop../1f.png) 但是当我用这个代码检查“sr”值时。。msgbox的展示恰到好处 private void button14_Click(object sender, EventArgs e) { if (
C:Users hesisdesktopredefenseresourceismagesred1f.png
),其中应该是这样的(C:P/Users/thesis/Desktop../1f.png
)
但是当我用这个代码检查“sr”值时。。msgbox的展示恰到好处
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");
}
}
为什么会这样 也许MySQL认为“\”字符是转义符,所以它不包含在字符串中。试一试
private void button14_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
MessageBox.Show(openFileDialog1.FileName);
}
}
插入时,转义字符将被转义
编辑:例如,像这样替换命令文本初始化行。还为单引号添加转义符
c.Replace(@"\", @"\\")
编辑:请参阅@Matthew的答案,了解更多“最佳实践”解决方案,使用参数化查询。这是由于您编写查询的方式。在MySQL中,反斜杠字符
\
(出现在文件路径中)具有特殊含义,即转义下一个字符。您需要对这些数据库进行编码,许多不同的数据库管理系统都有这样的模式
string escapedPath = c.Replace(@"\", @"\\").Replace("'", @"\'");
command.CommandText = ("Insert into data (path) values('" + escapedPath + "')");
除此之外,您的代码容易受到攻击
要解决这两个问题,可以使用参数化查询
string escapedPath = c.Replace(@"\", @"\\").Replace("'", @"\'");
command.CommandText = ("Insert into data (path) values('" + escapedPath + "')");
这个答案可能不是100%准确,因为我的计算机上没有MySQL,但如果它不起作用,希望它至少能为您提供一些关于如何解决这个问题的信息。为什么不使用参数化查询?您可以避免转义字符串的大部分麻烦,防止整个安全风险类别,如果这样做,还可以从查询缓存中获得一点点性能 通常,它看起来像这样:
public void InsertPath(string path)
{
string connString = "Server=Localhost;Database=test;Uid=root;password=root;";
using (var connection = new MySqlConnection(connString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO data(path) VALUES(?path)";
command.Parameters.AddWithValue("?path", path);
command.ExecuteNonQuery();
}
}
}
我已经很久没有写过任何明确的C#查询代码了(6个月左右),我不记得这是否完全正确,我知道MySql提供程序对命名参数使用了与MSSQL稍有不同的参数化约定(使用@path而不是?path),但这应该会让您走上正确的道路。有关可能与您相关的更多指导信息,请参阅。路径中的反斜杠=它们需要转义。对于初学者来说,Windows对本地文件路径不使用正斜杠。是的,Windows使用正斜杠(以及反斜杠)。在命令提示符下,使用CD“C:/Program Files”是的,使用反斜杠。。那么我如何修复它呢?尝试替换这一行,
string c=openFileDialog1.FileName代码>带有字符串c=openFileDialog1.FileName.Replace(@“\”,@“\”)代码>。是的,例如这里。但我的意思是,当您形成插入查询并添加“…+c+…”连接时。希望您的文件名中没有一个引号。这件事也解决了我的问题,而不使用上面的c。替换:)