c#中的查询混淆错误

时间:2016-06-17 23:50:12

标签: c# sql access

我遇到了一些代码生病的问题尝试做。我正在为供应商订单做一些事情,所以我有一个名为“encomendas_fornecedores”的表,其中包含一个自动增量字段,该密钥是销售代码,包含在EF中在数字之前(这是一个文本字段)。所以代码:

connection.Open();

        OleDbCommand comando1 = new OleDbCommand();
        OleDbCommand comando2 = new OleDbCommand();
        OleDbCommand comando3 = new OleDbCommand();
        comando1.Connection = connection;
        comando2.Connection = connection;
        comando3.Connection = connection;
        comando1.CommandText = "INSERT INTO encomendas_fornecedores (cod_encomenda_forn, cod_metodo, cod_forn, total_pagar_forn) VALUES('FO', '" + txtcodmetodo.Text + "', '" + txtcodforn.Text + "', '" + lbltotalapagar.Text + "'); ";// insert into table the values with a FO to cod
        comando1.ExecuteNonQuery();
        comando2.CommandText = "Select MAX(num_encomenda) From encomendas_fornecedores;";// selecting maximum num encomenda so i can isolate it and add to a text before(btw i do this in php/sql no problems
       int  numero = Convert.ToInt32(comando2.ExecuteScalar());//max num_encomenda
        string codencomendaforn= "EF"+Convert.ToString(numero);// sales code completed
        comando3.CommandText = "UPDATE encomendas_fornecedores SET cod_encomenda_forn = '"+codencomendaforn+"' WHERE num_encomenda = '"+ numero +"';";//query that is giving me the problems,it says something like "type of data incorrect in data expression"
        comando3.ExecuteScalar();//giving me error this line

        connection.Close();

但是现在这里抓住cod_encomenda_forn是文本和num_encomenda自动增量,因为它在sql中,我试图在文本框中显示查询是否有任何错误但似乎没有错误

1 个答案:

答案 0 :(得分:0)

"UPDATE encomendas_fornecedores SET cod_encomenda_forn = '"+codencomendaforn+"' WHERE num_encomenda = **'**"+ **numero** +"**'**;";//query that is giving me the problems,it says something like "type of data incorrect in data expression"

您正在将字符串numero传递给where语句,该语句似乎正在期待一个数字。只要它是数字它应该工作,但绝对不是gauranteed工作。其次,您将另一个codencomendaforn字符串传递给encomenda什么是encomenda的数据类型?

您似乎没有处理c#代码和SQL查询之间潜在的数据类型差异。另外单引号''围绕SQL语句中的值告诉数据库引擎它是一个字符串,即使它是' 1234'。虽然SQL会自动转换某些值,但它并不总是如此。此外,c#.net库在发送SQL语句之前还会查找一些转换等。要正确修复使用SQL表中数据类型的数据类型的参数。只需在声明中修复数据类型并修复&#​​39;'适当的单引号。

PS那些试图在评论中帮助你的人很善良,并告诉你在解决这个问题后毕业时保持工作的专业方法。