我正在尝试执行带有 where 子句的 SQL 语句,看起来像
string s2 = "Select * from idtyfile where oysterid=" + id ;
SqlCommand da2 = new SqlCommand(s2, con); or
SqlAdapter da2 = new SqlAdapter(s2, con);
当我尝试执行它们时,这两个都失败了
da2.ExecuteReader();
ID中的数据看起来像
ID
43PCOU5T
ZP6RAEJ0
出于某种原因,这两个查询都对这类数据失败。
最佳答案
您在 select 命令中缺少单引号,这是导致您的原始 SELECT
失败的原因。但是我想指出,您应该始终在 using
语句中参数化和封装您的 SqlCommand
/SqlConnection
。以下将是解决您的问题的更清洁更安全的方法。
string s2 = "Select * from idtyfile where oysterid=@id";
DataTable myDataTable = new DataTable();
using (SqlConnection conn = new SqlConnection(myConnectionString))
using (SqlCommand cmd = new SqlCommand(s2, conn))
{
cmd.Parameters.AddWithValue("@id", id);
conn.Open();
myDataTable.Load(cmd.ExecuteReader());
}
对于一些教育资源,您应该查看以下链接。
MSDN Reference for the using
keyword
MSDN Reference for SqlCommand
-- 查看 Parameters
属性。
关于c# - SqlDataAdapter、SqlCommand 从字符串中删除前导数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17176506/