views:

241

answers:

2

This this code:

SELECT SUBSTRING(posted,1,4) as year FROM styles
reader = cmd1.ExecuteReader(CommandBehavior.CloseConnection);
reader.Read();
Response.Write(reader[0].ToString());

I only get the string "System.Byte[]" printed out. How come?

If I use the software Mysql Query Browser I get the actual string from my database.

I understand that "Byte[]" is an arraylist but how do I convert this to a pure string?

The "posted"-field in my database contains a date like "2010-04-04 13:23:00" and I want to get only the year by using SUBSTRING.

A: 

You will need to use the .GetString

ie

reader[0].GetString(0);

Additionally you can use the MySQL YEAR function to extract the year from your date.

ie

SELECT YEAR(date_field) FROM table
John M
Very nice! Thank you. :)But it didn't work with "reader[0].GetString(0)"I used "reader.GetString(0)". :)But now I got to a second problem too... I need to select this with DISTINCT and when I use "SELECT DISTINCT SUBSTRING(posted,1,4) as year FROM styles" I get nothing even tho' my table has 10 rows in it.
theSwede
@theSwede - What happens if you use the YEAR() function instead of SUBSTRING()?
John M
Same thing. I get the string as a "System.Byte[]" and have to convert it.But actually I need to put this in a repeater and in the webform im using "<%# DataBinder.Eval(Container.DataItem, "posted") %>" to print the year but how do I run the "GetString()" on that code?
theSwede
A: 

The correct query is

SELECT DISTINCT SUBSTRING(CONVERT(varchar, posted, 111),1,4) as year FROM styles

It equals to

SELECT STR(YEAR(posted)) as year FROM styles-- YEAR returns int statement

First argument is converted, than substring extracted. 111 - the convertion format: http://www.mssqltips.com/tip.asp?tip=1145

Also try

reader["year"].ToString();

as far as you use this alias.

LexRema