我正在尝试查询表以查找如下记录:
string owner = "sometextlikethis";
string pictureName = "pexels-photo.jpg_15-Apr-19 07:59:37"; //problem
PictureLibrary _pictureObj = new PictureLibrary();
var connString = db.connStringCompany;
string cmdText = "SELECT ID FROM PictureLibrary WHERE CONVERT(VARCHAR, PictureOwner) =@PictureOwner AND CONVERT(VARCHAR, PictureName) =@PictureName;";
using (var connection = new SqlConnection(connString))
{
using (var sqlCmd = new SqlCommand(cmdText, connection))
{
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "@PictureOwner";
param1.Value = owner;
sqlCmd.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "@PictureName";
param2.Value = pictureName;
sqlCmd.Parameters.Add(param2);
connection.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read()) //record with matching owner is found but if I add pictureName as additional parameter reader does not find anything
{
_pictureObj.Id = Convert.ToInt32(dr["ID"]);
}
connection.Close();
}
}
return _pictureObj;
当我运行查询时,ID为null,因为读取器没有找到任何东西。我尝试了不带pictureName参数的查询,它工作正常。
我还检查了给定PictureOwner和PictureName匹配查询存在的表和记录。
我猜我在查询参数包含":"冒号的记录时遇到了问题。我正在使用文件名和当前日期连接来创建图像名称,然后再将其插入SQL。
我应该改变文件的命名以避免冒号吗?
编辑:
问题不在于冒号":",而在于查询中缺少VARCHAR
的长度。
1条答案
按热度按时间jtoj6r0c1#
这里的问题应该是您将
PictureOwner
转换为VARCHAR
,这将截断您的字符串。