2

我有这段代码,我想让它变成 varchar 而不是字符串。在 c# 中执行此操作的适当语法是什么

 string emri = row["Nome"].ToString();

我有一个必须运行的查询,我在其中使用 emri 并将它与我在 mysql 中创建的表中的列进行比较。mysql 中的列是 varchar(20) 类型。当我执行我的代码时,它在我的查询中给出了一个错误,我猜可能是因为这个原因

I have this query 
string query = "IF NOT EXISTS(SELECT * FROM clienti WHERE CodCliente=   " + id + "  AND Nome = '" + emri + "' AND RagioneSociale=' " + ragSoc + " ' AND PartitaIVA=' " + piva + " ') INSERT INTO clienti VALUES(" + id + " ,' " + emri + " ',' " + ragSoc + " ',' " + piva + " ') else UPDATE clienti SET( " + id + " ,' " + emri + " ',' " + ragSoc + " ',' " + piva + " ')";

它给了我这个问题

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS(SELECT * FROM clienti WHERE CodCliente=   1  AND NomeCliente = 'Jo' at line 1
4

3 回答 3

18

C#中没有varchar类型。

Avarchar几乎是一个字符串(显然在 SQL 中是可变长度的),所以你所拥有的很好。

于 2013-04-19T20:28:36.407 回答
2

在 .NET 中没有名为“varchar”的类型,你得到的最接近的是string.

我假设您要问是有原因的,并且我猜您在问题中发布的代码存在一些问题,所以让我尝试猜测那是什么,并告诉您如何解决这个问题。

首先,由于varchar不存在,因此您发布的代码在表面上看起来不错。

但是,有一个问题,你没有显示是什么row,但如果它是常见的罪魁祸首之一,你就会遇到null来自数据库的标记问题。

对于您的 .NET 代码,数据库中相应列中的null标记将不会返回null,而是您将返回一个DBNull.Value值。

这是我要写的:

string emri;
if (row["Nome"] == DBNull.Value)
    emri = null; // or String.Empty if you don't like null values
else
    emri = Convert.ToString(row["Nome"]);
于 2013-04-19T20:35:28.863 回答
2

NO this is untrue, When you step through a process by changing the debugging settings located in VS you can step through a SQL script process also if you run an example like this where a table has varchar values set into it.

Try
{
  using (SqlCommand cmd = new SqlCommand(examplestring, connection))
  {
    cmd.ExecutenonQuery();
  }
 }
 catch
 {
    return;
  }

now put a breakpoint onto the catch statement and in the examplestring have a string called '456789 - 1' equal to Itemnumber varchar(25) in the SQL table.

The catch will get the following error SqlException was caught - Error converting data type varchar to numeric.

Now query string is set as a string cause that is the only way the SqlCommand works look it up on MSDN : System.Data.SqlClient.SqlCommand

So yes Lasse there is varchar in .NET.

于 2014-10-03T19:35:01.807 回答