提问人:SoloWharf 提问时间:11/4/2023 更新时间:11/5/2023 访问量:54
如何在 C 中将路径作为参数传递给 MySQL 查询#
How do you pass a path as a parameter to a MySQL query in C#
问:
我正在尝试将图像的路径和文件名保存到表格中,但它不起作用。AddParameterWithValue 成员似乎将我传递的字符串中的所有斜杠加倍,然后 ExecuteNonQuery 引发错误。我到处找,找不到解决方案。
该表称为“images”,有三列:id(自动递增的 int)、path(字符串)、filename(字符串)。
这是我的代码:
using (MySql.Data.MySqlClient.MySqlConnection mySqlConnection = new MySql.Data.MySqlClient.MySqlConnection(Settings.Default.tlConnectionString))
{
try
{
mySqlConnection.Open();
string cmdText = "INSERT INTO images ('path', 'filename') VALUES (@path, @filename);";
MySqlCommand cmd = new MySqlCommand(cmdText, mySqlConnection);
cmd.Parameters.AddWithValue("@path", @Path.GetDirectoryName(itemFilePath));
cmd.Parameters.AddWithValue("@filename", Path.GetFileName(itemFilePath));
cmd.ExecuteNonQuery();
long imageId = cmd.LastInsertedId;
// more code here ...
}
catch (Exception e)
{
return false;
}
}
return true;
我收到的错误消息是这样的:
{“你的 SQL 语法有错误;查看与您的MySQL服务器版本相对应的手册,了解在''path', 'filename') VALUES ('\\\\\1215608140\\
您会注意到,它使所有反斜杠加倍。
正确的语句应该是
插入 。(, )值 ('\\\\srvdata\\images\\products', '8418-(1215608140).jpg');
myschema
images
path
filename
答:
1赞
Revanth Shalon
11/4/2023
#1
我尝试了这段代码,它对我有用。你能再检查一次这是否有效吗?此处唯一的更改是将 CommandType 添加为 CommandType.Text 并从命令文本中删除引号
//Assuming this correct file path
string filePath = @"\\srvdata\images\products\8418-(1215608140).jpg";
using(var mySqlConnection = new MySQl.Data.MySQlClient.MySQlConnection(Settings.Default.tlConnectionString)
{
try{
mySqlConnection.Open();
string commandText = "INSERT INTO images (path, filename) VALUES (@path, @filename);";
var cmd = new MySqlCommand(commandText, mySqlConnection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@path", Path.GetDirectoryName(filePath));
cmd.Parameters.AddWithValue("@filename", Path.GetFileName(filePath));
int result = cmd.ExecuteNonQuery();
if(result!=-1)
{
Console.WriteLine("Success");
}
else
{
throw new Exception("Failure");
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
mySqlConnection.Close();
}
}
评论
0赞
Bradley Grainger
11/5/2023
@gunr2171 正如您已经指出的,这是解决 OP 问题需要进行的唯一更改。(您可以考虑将其添加为答案;我会投赞成票。
0赞
SoloWharf
11/6/2023
谢谢 Revanth,也在这里工作。👌
评论
Path.GetDirectoryName(itemFilePath)
'path', 'filename'