Вопрос

I have searched and found surprisingly few results. I found that there is some datatype property for DataColums, but when retrieving data from a SQL server database, what is the datatype of whatever is retrieved? I'm working with a SqlDataAdapter to fill a DataTable. To get the values, I work as follows:

DataTable dtt = Database.get(SQLString); //pseudo-code
string value = dtt.Rows[0][0]; //Or is this a string?

So what is in dtt.Rows[0][0] if the database column datatype is bigint, int, date or bit? Do I need to convert them to string first and then convert them to other datatypes I require?

Это было полезно?

Решение

Well it depends how is defined in database, for example let's say that you have this table :

CREATE TABLE [dbo].[Test](
    [ID] [int] NOT NULL,
    [Name] [nvarchar](128) NOT NULL,
    [Birthday] [datetime]) 

then you can access first row like that :

DataTable dtt = Database.get("Select * from Test"); //pseudo-code
DataRow rw = dtt.Rows[0];
int id = rw.Field<int>("ID");
string name = rw.Field<string>("Name");
DateTime dt = rw.Field<DateTime>("Birthday");

or

DataTable dtt = Database.get("Select * from Test"); //pseudo-code
int id = (int) dtt[0]["ID"];
string name = (string) dtt[0]["Name"];
DateTime dt = (DateTime) dtt[0]["Birthday")];

Другие советы

So what is in dtt.Rows[0][0] if the database column datatype is bigint, int, date or bit?

A boxed Int64, a boxed Int32, a boxed DateTime and a boxed Boolean, respectively. This is why the return type of this expression is Object - so that it can return a value of an appropriate type. All you need to do (knowing what type should have been returned) is insert a cast/unbox - unless you wish to continue treating them all as Objects.

And I agree with Antonio's comment - it would be preferable to be accessing columns by name rather than by ordinal position - you can either use the overloaded operators which accept strings rather than ints, or at the least, use IndexOf() to look up the columns ordinal position at runtime.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top