How to use the varchar data type in c#?

后端 未结 3 569
时光取名叫无心
时光取名叫无心 2021-01-22 23:24

I have this piece of code and I want to make it varchar not string. What is the appropriate syntax to do that in c#

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


        
相关标签:
3条回答
  • 2021-01-22 23:41

    In .NET there is no type named "varchar", the closest thing you got is string.

    I'm assuming there is a reason you're asking, and I'm guessing you're having some problems with the code you've posted in the question, so let me try to guess what that is, and tell you how to solve it.

    First, since varchar doesn't exist, the code as you've posted it looks fine, on the surface.

    However, there is a problem, you don't show what row is, but if it is one of the usual culprits, you're going to run into problems with null marks from the database.

    A null mark in the database in the corresponding column will not be returned as null to your .NET code, instead you're going to get back a DBNull.Value value.

    Here's what I would write instead:

    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"]);
    
    0 讨论(0)
  • 2021-01-22 23:46

    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.

    0 讨论(0)
  • 2021-01-23 00:02

    There is no varchar type in C#.

    A varchar is pretty much a string (of variable length in SQL, obviously), so what you have is fine.

    0 讨论(0)
提交回复
热议问题