[Dataset] How to get datatype for each column?

Hello

	A DB-unaware grid offers better performance and knows how to handle
sorting if columns are created that match the type of data they
contain, eg. numeric data should be fed to a numeric column, dates to
a date column, etc.

I've never used the TDataSet's Fields[index].DataType and
Fields[index].FieldKind, and was wondering if someone had some basic
example on how to use them?

Thank you.
0
Gilles
10/21/2009 5:19:03 PM
embarcadero.delphi.database 1294 articles. 0 followers. Follow

5 Replies
7719 Views

Similar Articles

[PageSpeed] 41
Get it on Google Play
Get it on Apple App Store

> {quote:title=Gilles Ganault wrote:}{quote}
> I've never used the TDataSet's Fields[index].DataType and
> Fields[index].FieldKind, and was wondering if someone had some basic
> example on how to use them?

This should get you started:

{code}
with YourDataSet do
begin
  for i := 0 to FieldCount - 1 do
  begin
    if Fields[i].Lookup then
      ShowMessage(Fields[i].FieldName + ' is a lookup field')
    else if Fields[i].Calculated then
      ShowMessage(Fields[i].FieldName + ' is a calculated field')
    else
    begin  // FieldKind should be ftData here, but might be ftAggregate or ftInternalCalc.
      if Fields[i].FieldKind = ftData then
      begin
        case Fields[i].FieldType of
          ftString: ShowMessage(Fields[i].FieldName + ' is a string field');
          ftInteger: ShowMessage(Fields[i].FieldName + ' is an integer field');
          ftFloat: ShowMessage(Fields[i].FieldName + ' is a float field');
          ftDate: ShowMessage(Fields[i].FieldName + ' is a date field');
          ftBoolean: ShowMessage(Fields[i].FieldName + ' is a boolean field');
          // Continue with other possible FieldType values 
        end;
      end;
  end;
end;
{code}
0
Ken
10/21/2009 6:48:59 PM
On Wed, 21 Oct 2009 11:48:59 -0700, Ken White <> wrote:
>This should get you started:

Thanks much for the code :-)

Since the BDE-like interface seems to be able to return quite a few
datatypes although SQLite itself is very basic (TEXT, NUMERIC,
INTEGER, REAL, NONE), I was wondering if there were a way to simply
display the raw type for each column so I can tell how they are mapped
to Delphi, such as:

-----------
ASQLite3Query1.SQL.Text := 'SELECT * FROM mytable';
ASQLite3Query1.Open;

for mycol := 0 to ASQLite3Query1.FieldCount - 1 do begin
  //E2250 There is no overloaded version of 'IntToStr' that can be
called with these arguments
  ShowMessage(IntToStr(ASQLite3Query1.Fields[mycol].DataType));

  //E2089 Invalid typecast
  ShowMessage(String(ASQLite3Query1.Fields[mycol].DataType));
end;
-----------

Thank you.
0
Gilles
10/21/2009 10:48:46 PM
"Gilles Ganault" <nospam@nospam.com> wrote in message 
news:175415@forums.codegear.com...
> On Wed, 21 Oct 2009 11:48:59 -0700, Ken White <> wrote:
>>This should get you started:

This is from an earlier post:

Something like the following(untested).

uses
  TypInfo;

var
  aDataType: TDataType;

aDataType := MyQuery.FieldByName('FieldName').DataType;

ShowMessage(GetEnumName(TypeInfo(aDataType), Ord(aDataType));

Regards, Paul.
0
Paul
10/21/2009 11:52:15 PM
> {quote:title=Gilles Ganault wrote:}{quote}
> ASQLite3Query1.SQL.Text := 'SELECT * FROM mytable';
> ASQLite3Query1.Open;
> 
> for mycol := 0 to ASQLite3Query1.FieldCount - 1 do begin
>   //E2250 There is no overloaded version of 'IntToStr' that can be
> called with these arguments
>   ShowMessage(IntToStr(ASQLite3Query1.Fields[mycol].DataType));

Change to 

{code}
ShowMessage(IntToStr(Ord(ASQLite3Query1.Fields[myCol].DataType)));
{code}

Note the use of Ord() in the conversion.

>   //E2089 Invalid typecast
>   ShowMessage(String(ASQLite3Query1.Fields[mycol].DataType));

This is as expected. DataType is not a string, and therefore can't be typecast to a string.
0
Ken
10/22/2009 5:13:49 PM
On Thu, 22 Oct 2009 10:13:49 -0700, Ken White <> wrote:
>This is as expected. DataType is not a string, and therefore can't be typecast to a string.

Thanks everyone for the help.
0
Gilles
10/30/2009 12:17:01 PM
Reply:

Similar Artilces:

Get database Column datatypes and lengths
I have a query that gets me table names and all the column names associated with the table from a database. Does anyone know of away to get the column datatypes and lengths ? Here is a code sample of trying to get the column info that does not seem to work: transaction_1->ListTables(*query_1, "", "", "", "" ); index3 = query_1->GetColumn("TABLE_NAME").GetIndex(); transaction_2->SetUserid(transaction_1->GetUserid()); transaction_2->SetPassword(transaction_1->GetPassword()); transaction_2->SetDataSource(transacti...

Is there any tool in .Net to collect database columns'name,datatype and create get/set function in class automatically?
Hi there, I have some big tables with many columns, I want to write classes to include all the columns, it's too time-consuming to write codes by hand. I wonder if there is a tool or any simple ways in .Net to collect database columns'name,datatype and create get/set function in class automatically? Any ideas are appreciated. CodeSmith has a strongly typed collections (which is what it sounds like you want) generator. It's free. Find out more here: http://www.ericjsmith.net/codesmith/ No, I don't get any money or anything for sending you there. I just use it ever...

Column Datatype in DataSet
I have a DataSet filled by a sqlDataAdaptor that I use to export into excel. The problem is none of the columns get the datatypes from the database, they are all strings. So the excel is not formatted correctly. Is there a way to set each column's datatype when I fill the DataSet. I know I could make a TypedDataset xsd but that would make for days of rework. Also, I can't just say column 11 is of this type because the request to the DB is made at runtime and the commandtext can be different each time. I also know already that I can't change the datatype once there is data in the ds. ...

Get Column datatype
Hi, I want to select the datatype of a column. But I don't know how to select, can anyone give me some hints? Thanks a lot. For example: db name: Test col datatype c1 varchar c2 char c3 ntext when I select the column c3, it will return the ntext. For Sql Server or MSDE you can use: SqlDataAdapter schemaDA = new SqlDataAdapter("SELECT TABLE_CATALOG,TABLE_NAME,COLUMN_NAME,ORDINAL_POSITION,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE '" + yourTableName...

Getting Column Datatype
Hi, I'm using PB 7.5. I need to get the datatype for a bunch of columns in a loop using dot notation. I have the column name assigned into a variable. Is there a way to use something like: ls_coltype = dw_1.Object.columnname.ColType substituting the variable, ls_colname for columnname. I thought it could be done using Modify, but I can't remember how. Thanks, Jim You can do it using the describe method: <DW Control Name>.Describe("<Columnname>.Coltype") so in your case: ls_coltype = dw_1.Describe(ls_colname + ".Coltype") ...

Error: "receiver invalid column lenght from bcp client" Bulk copy from Oracle Database to SqlServer database using Dataset
I want to export data from Oracle database tables to Sqlserver database tables. using VS.NET 2005(Windows application). I have created same table structure in SQL server to export the data using Dataset.  I am getting error : "receiver invalid column lenght from bcp client" " bulkcopy.WriteToServer(ds1.Tables[0]);private void button3_Click(object sender, EventArgs e) {string constr1 = "data Source=oracle;user id=scott;password=tiger";OracleConnection conn2 = new OracleConnection(constr1); conn2.Open(); string sql1 = "select * from " + textBox4....

Custom DataType column in DataSet
Hi,I am trying to use a custom data type for a DataSet table column, however I keep getting the error: "Column requires a valid data type". Looking at the XSD file the data type is set to: msdata:DataType="NameSpace.Class, Assembly, Version=8.0.3.1, Culture=neutral, PublicKeyToken=null" The odd thing is that other people can view exactly the same DataSet on their machine, its only me thats having the problems. I've tried setting the type to a class from a third party library and it accepts it fine, but even a simple test class in the same namespace as the Da...

Get Column Names in DataSet
Using Asp.Net/C# I want to extract the column names in a select query, place the data in a dataset, then bind the column names in a dropdownlist (with DropDownList1 as its ID)Example:    stringQuery = "Select * from tableName";     DataSet ds = new DataSet();    DropDownList1.DataSource = ds.Tables[0].DefaultView;     DropDownList1.DataTextField = "ColumnOne";    DropDownList1.DataBind(); If I bind the values of a certain field/column (ColumnOne), the list is binded in the dropdownlist .B...

Getting dataset from database through atlas...
Hi all, I am using Atlas in one of my projects. The scenario is that I want to get dataset from database. I am accessing database using MS Enterprise Library 2006. The database is SQL Server 2005 and .NET Framework is 2.0. I have created a WebMethod using Atlas. Every thing is working fine up till now. The problem is that when I invoke dataaccess method to get dataset from database, it seems that execution to that method is by passed. As soon as a method is called from code behind which has code to call dataset from database, no error is returnd but my js function isn't execu...

DataSet auto column datatype
Hi I am using OleDbDataAdapter for reading the csv file my code is like this:--private DataSet Read(string folderPath,string filename) {string m_ExtendedProperty = "\"text;HDR=NO;FMT=SemicolumnDelimited\""; string m_Query = "Select * from " + filename;DataSet ds = new DataSet("Data");OleDbDataAdapter m_DataAdapter = new OleDbDataAdapter(m_Query, "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + folderPath + ";Extended Properties=" + m_ExtendedProperty + ""); m_DataAdapter.Fill(ds); return ds;   } My Pr...

how to get the DataType of Column in dataview
hi how to get the DataType of Column in dataview?thanks  Hi:   Have a look at this sample: using System.Data.SqlClient; protected void Button1_Click(object sender, EventArgs e)    {        SqlConnection sc = new SqlConnection(ConfigurationManager.ConnectionStrings["Pubs"].ToString());        SqlCommand sm = new SqlCommand("Select * from table1",sc);        SqlDataAdapter sa = new SqlDataAdapter(sm);        DataTable dt ...

How to get DataType of Column in Table ?
I want get DataType of Column in Table ex: nvarchar, varchar, etc... Help me !!I'm from Vietnam Viva Vietnam You should try DataType property as follows Table.Columns(IndexOfColumn).Datatype sp_Columns @Table, @Database afaik. unless you want the info like how lonelytrooper showed.Kay LeeMySpace.com - http://www.myspace.com/kragieInfrastructure GroupMySpace.com- Code to live, but Live to code....

converting a dataset/datagrid column datatype
Please help I am doing SUM of a dataset column Int32 datatype. ds.Tables(0).Compute("Sum(intVal)", "") e.g. myresult = 382931 Dim inTime as Integer ' I use a time span to format the value to show time spend. Dim ts As TimeSpan = New TimeSpan(0, 0, 0, inTime, 0) myNewRow = ts.Hours & ":" & ts.Minutes & ":" & ts.Seconds ' myNewRow becomes one of the columns that I add to mydataTable MydataTable.items.add(myNewRow) for example my column value = 10:22:11. Because this is now a string I cannot append it to the ...

column datatype in oracle and dataset table
 Hi all,I have an Oracle table with column of datatype NUMBER(10). When I add a tabledapter in dataset designer, it creates a table with a column of datatype: system.decimalI change it to system.int32, but when I use an insert query, the parameter is of decimal format. I changed the type in designer.vb (although it is not recommended) and it worked fine. but after time, it revoked back to decimal.Am I missing something, or it is just another oracle, .NET misunderstanding?  I would appreciate any feedback,Thanks,  I found the solution. When creating the Insert query, it ...

Web resources about - [Dataset] How to get datatype for each column? - embarcadero.delphi.database

UAH satellite temperature dataset - Wikipedia, the free encyclopedia
The UAH satellite temperature dataset , developed at the University of Alabama in Huntsville , attempts to infer the temperature of the atmosphere ...

Data : Where can I get large datasets open to the public?
Answer (1 of 91): Here's the ones I've found most useful: CrunchBase, US Census, Google Public Data, Infochimps, Timetric, Factual, Freebase, ...

YouTube - Hans Rosling: Let my dataset change your mindset
Hochgeladen am 31.08.2009 http://www.ted.com Talking at the US State Department this summer, Hans Rosling uses his fascinating data-bubble software ...

The Mindset, Skillset, Dataset Approach to Social Media
... Social media is comprised primarily of unstructured data, which is difficult to analyze. A new approach called Mindset, Skillset, Dataset can ...

Sending large datasets to Amazon? Use the Post Office
Amazon has introduced a new method to move large amounts of data to and from …

Yahoo Releases the Largest-ever Machine Learning Dataset for Researchers
Yahoo is announcing the public release of the largest-ever machine learning dataset to the research community.

IDG Contributor Network: Are datasets truly anonymized? Two well-suited researchers are going to find ...
With little fanfare or formality, Adam Smith , associate professor of computer science and engineering in Penn State's School of Electrical Engineering ...

House GOP looks to shed light on EPA secret datasets
House Republicans have introduced a bill that would block the Environmental Protection Agency from crafting regulations based on “secret” scientific ...

Google Making It Easier to Transfer Huge Datasets on the Cloud
... Cloud Import services are now in preview mode, but could later be available on a widespread basis to help enterprises move their large datasets ...

Environmental datasets, reverse auction legislation and military email
News and notes from around the federal IT community. The White House's Data.gov has added five datasets to the Ecosystem Vulnerability theme ...

Resources last updated: 2/5/2016 6:00:59 PM