Ned
Ned

Reputation: 355

Column Doesn't Exist server error - but sql server management says it does

i'm trying to import a field from a mysql 2008 database. I wrote this small code (that i used a few times ago) - and it keeps giving me this server error:

Column 'Previous Login' does not belong to table Table.

Line 47: DateTime userEntry = Convert.ToDateTime(ds1.Tables[0].Rows[0]["Previous Login"]);

But it does exist! when i use the same query insql server management it works fine so i guess the return data is good , any idea where i'm going wrong?

Thank you!

    {
    SqlConnection con = new SqlConnection();
    con.ConnectionString = "server=(local);database=PhilipsMaterials;Integrated Security=SSPI;";
    con.Open();
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    // SQL Query that returns only the messages from the last 2 weeks starting with the most recent one.
    string sql = "Select * From Messages Where DATEDIFF(DAY,Date,GETDATE()) <= 14 ORDER BY Date Desc";
    SqlDataAdapter da = new SqlDataAdapter(sql, con);
    da.Fill(ds);
    dt = ds.Tables[0];
    showMsgs.DataSource = ds;
    showMsgs.DataBind();

    // new message notification
    string username = Convert.ToString(Session["username"]);
    username = username.Substring(username.IndexOf("\\") + 1);

    DataSet ds1 = new DataSet();
    DataTable dt1 = new DataTable();
    string sqluser = "Select * From [PhilipsMaterials].[dbo].[Employees] Where username='" + username + "'";
    SqlDataAdapter da1 = new SqlDataAdapter(sqluser, con);
    da.Fill(ds1);
    dt1 = ds1.Tables[0];
    DateTime userEntry = Convert.ToDateTime(ds1.Tables[0].Rows[0]["Previous Login"]);

    DateTime lastMsg = new DateTime();
    lastMsg = Convert.ToDateTime(ds.Tables[0].Rows[0]["Date"]);
    int compared = DateTime.Compare(userEntry, lastMsg);
    if (compared < 0) { notification.Visible = true; }
    con.Close();
} 

Upvotes: 1

Views: 987

Answers (1)

Daniel Br&#252;ckner
Daniel Br&#252;ckner

Reputation: 59705

If your column name contains spaces you need some kind of escaping - try using [Previous Login] as column name in the same way you do it in your SQL statements.

And - as mentioned in the comment to the question - have a look at SQL injection and how to avoid it.

Upvotes: 1

Related Questions