在Where子句中具有两个条件的和的SQL语句错误

时间:2017-03-22 05:14:59

标签: c# mysql visual-studio

好的,所以我使用MVS 2015来使用Windows Forms和C#来修复数据库 这是我编码的

string queryString = @"SELECT VALUE P FROM Tblproducts as P";

foreach (tblproducttype pt in cse.tblproducttypes)
{   
    ObjectContext context =((IObjectContextAdapter) cse).ObjectContext;
    ObjectQuery<tblproduct> filteredproduct = new ObjectQuery<tblproduct>(queryString, context);

    foreach (tblproduct tprod in filteredproduct)
    {
        Button b = new Button();
        b.Text = tprod.description;
        tp.Controls.Add(b);
    }
}

我收到一个例外,说明列名称'Parts'不是有效的列名。当“Parts”是发送给函数的类型字符串时。

5 个答案:

答案 0 :(得分:0)

您需要引用type参数,否则它将被解释为列名而不是值:

string query = "SELECT SUM(TotalReceiptAmount) " +
               "FROM Expense WHERE ProjectID = " + 
               parsedProjectID + " AND Type = '" + type + "'";

                                              ^            ^

更好的是使用prepared statements

  1. 自动处理参数类型;
  2. 保护您的代码免受sql injections;
  3. 的攻击
  4. 优化查询执行。

答案 1 :(得分:0)

typevarchar/string类型,用引号括起来:

string query = "SELECT sum(TotalReceiptAmount) " +
                    "FROM Expense WHERE ProjectID = " + 
                    parsedProjectID + " AND Type = '" + type + "'";
                                                   ^____________^

为了更好的可读性,请为varchar/string类型执行此操作:

type = "'" + type + "'";
string query = "SELECT sum(TotalReceiptAmount) " +
                    "FROM Expense WHERE ProjectID = " + 
                    parsedProjectID + " AND Type = " + type ;

答案 2 :(得分:0)

It seems like the string that you send to function - 'Parts' should be in quotes  when you compare for e.g. the resulting query from your code should  be :
SELECT sum(TotalReceiptAmount) FROM Expense WHERE ProjectID =                        parsedProjectID AND Type = 'Parts';

答案 3 :(得分:0)

新错误对象无法从DBNull转换为其他类型。

使用

internal static decimal getExpenseSum(int parsedProjectID, string type)
    {
        decimal value = decimal.Zero;
        type = "'" + type + "'";
        string query = "SELECT sum(TotalReceiptAmount) " +
                        "FROM Expense WHERE ProjectID = " + 
                        parsedProjectID + " AND Type = " + type;
        SqlCommand cmd = new SqlCommand(query, conn);
        conn.Open();
        value = Convert.ToDecimal(cmd.ExecuteScalar());
        conn.Close();
        return value;
    }

答案 4 :(得分:0)

好的,这样可行但我正在为“”部分“”“”工具“”和“”“其他”做三次,当然我只是输入了一个部件,然后表格又回到了项目形式,并试图做theese总和,并有工具和其他的空值。所以我要做一个尝试捕捉.....  但是谢谢大家的解决.... 如果你要工作流程添加客户,那就是我项目的核心.... 现在,将项目添加到现有客户,然后报告。 YEAH再次感谢你