我试图从一个wpf datagrid单击的单元格中获取正确的字符串,我将在sql select语句中使用它到第二个wpf数据网格。输入静态字符串值时,它将起作用,但不能从动态字符串中起作用。我的代码出了什么问题?
private void dataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataRowView row = (DataRowView)dataGrid1.SelectedItems[0];
string barcode_string = row["BarCode"].ToString();
//string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = '" + barcode_string + "'";
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = 'L002BO4'";
}
当在sql语句中输入字符串时,它就像一个魅力,但是当然我希望从大型数据库返回的动态字符串也能正常工作。
请不要在SQL语句中连接字符串。使用参数。检查数据库以查找BarCode列的正确数据类型。
private void DataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataTable dt = new DataTable();
DataRowView row = (DataRowView)dataGrid1.SelectedItems[0];
string barcode_string = row["BarCode"].ToString();
//string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = '" + barcode_string + "'";
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = @BarCode;";
using (SqlConnection cn = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand(barcode_detail, cn);
cmd.Parameters.Add("@BarCode", System.Data.SqlDbType.VarChar).Value = barcode_string;
cn.Open();
dt.Load(cmd.ExecuteReader());
//use the data in the data table
}
}
编辑测试字符串。添加using System.Diagnostics
以使用Debug.Print
String literal = "L002BO4";
String variable = row["BarCode"].ToString();
if (literal.Length == variable.Length)
Debug.Print("The length of the strings match");
else
Debug.Print("The lengths do not match");
Char[] variableArray = variable.ToCharArray();
Char[] literalArray = literal.ToCharArray();
for (int index =0; index<literalArray.Length; index++)
{
if (variableArray[index] == literalArray[index])
Debug.Print($"index {index} matches");
else
Debug.Print($"index {index} does not match");
}
您在最后一个查询中错过了一个"
。试试这个
string barcode_detail = "SELECT BarCode, PCBGUID
FROM TB_AOIResult WHERE
BarCode = "+"\'" +barcode_string + "\'";
你能尝试下面这个吗?
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = "+ barcode_string;