c# - SqlDataAdapter、SqlCommand 从字符串中删除前导数字

标签 c# sqlclient

我正在尝试执行带有 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/

相关文章:

c# - 对可能未打开或关闭的 SqlConnection 调用 Close

aws-lambda - 使用 C# AWS Lambda 函数连接到 SQL Server Express 时遇到问题

c# - 将 A 转换为 1 B 转换为 2 ... Z 转换为 26,然后将 AA 转换为 27 AB 转换为 28(在 Excel 中将列索引转换为列引用)

c# - TextTransform.exe 似乎只接受旧版本的 C#

c# - 绑定(bind)用户控件值并添加填充

.net - SqlDataReader.GetSqlBinary 与 SqlDataReader.GetSqlBytes?

sqlclient - 无法加载 .Net Standard 2.0 类库中的文件或程序集错误

C# 更改数组中的维数

c# - 用于清除文本区域/文本框内容的按钮