怪事呀,代码如下:
DB d = new DB();
//string sql = "Select BarcodeType,BarcodeContext From BarcodeTable Where Barcode='"+textBox1.Text.Trim()+"'";
//string sql = "Select Barcode,Barcodetype,barcodecontext from barcodetable";
string sql="Select barcode,barcodetype,barcodecontext from barcodetable where barcode like '%"+textBox1.Text+"%'";
DataTable dt1 = new DataTable();
dt1 = d.SelectContext(sql);
dataGrid1.DataSource = dt1;
代码中,加入了Where 就无法取到数据,删除条件后就可以取到二条记录。WHY?
再试着用了一个模糊条件查询发现可以取到数据了,但这个又想到一个问题,我的数据库中barcode字段是nvarchar(50)null属性的。
是不是用=来精确查询时barcode字段中存在了空格这样的问题呢?但nvarchar不是一个变长的字段吗?太奇怪了!
public DataTable SelectContext(string sql)
{
SqlCeConnection conn=opensqlce();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
try
{
SqlCeCommand cmd = new SqlCeCommand(sql, conn);
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
da.Fill(ds);
dt = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return dt;
}
private SqlCeConnection opensqlce()
{
string ceConnStr = @"Data Source ="+System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\TPM.sdf";
SqlCeEngine engine = new SqlCeEngine(ceConnStr);
SqlCeConnection connMobile = new SqlCeConnection(ceConnStr);
try
{
connMobile.Open();
}
catch (Exception ex)
{
MessageBox.Show("不能连接数据库!" + ex.Message);
return null;
}
return connMobile;
}
调试的结果如下,就是找不到正确的数据。
在数据库中的截图如下:
没有正确的数据返回,试过DataReader更是错误报hasRows出错,讲不支持此属性。