GladiatoR
GladiatoR

Reputation: 21

How to read from mysql datetime field

I'm trying to read from mysql field with datetime type and I was trying everything and always it's return field name only.

Here is my code:

using (MySqlConnection connection = new MySqlConnection(ConnectionString))
{
    connection.Open();

    string query = @"SELECT `sID`, 'sDate', `sGameLogin`, `dGameAmount`, 
                    'sPayMethod' FROM `XeronRequests` WHERE `iStatus` = 0";

    MySqlCommand cmd = new MySqlCommand(query, connection);
    cmd.CommandType = CommandType.Text;

    using (MySqlDataReader dataReader = cmd.ExecuteReader())
    {                    
        while (dataReader.Read())
        {
            list.Add(new PaymentInfoText(dataReader["sID"] + "", 
                     dataReader["sDate"] + "", 
                     dataReader["sGameLogin"] + "", 
                     dataReader["dGameAmount"] + "", 
                     dataReader["sPayMethod"] + ""));
        }
    }

    e.Result = list;
}

Upvotes: 0

Views: 4014

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460038

Use

dataReader.GetDateTime(dataReader.GetOrdinal("sDate"))

instead of

dataReader["sDate"] + ""

and remove the ticks around your columns in the sql, e.g.

sDate instead of 'sDate'. You need them only for reserved words or if you have spaces in your column names:

9.3. Reserved Words

2.2. Reserved Words in MySQL 5.1

Upvotes: 3

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

The issue is your SELECT statement, you have single quotes ' instead of back ticks around sDate and so the value of that field is in fact "sDate".

Or as Jon Skeet stated, get rid of the back ticks entirely because they exist for keywords only, must like the [] do for MSSQL.

Upvotes: 0

Related Questions