C#/ MySQL - 从数据库中获取日期

时间:2014-08-22 14:58:41

标签: c# mysql date

在我的数据库中,我从类型日期开始有一行。我想在我的C#程序中显示这些日期,但是我在编写查询时遇到了问题。目前我尝试使用:

public string getAge(string Name) 
    {
        connection con = new connection(); //The object for the class with the connection string 
        con.conopen(); //opens the connection
        string Age = "";
        MySqlCommand cmd_getAge = new MySqlCommand("Select 'Age' from profile where Name = '" + Name + "';", con.con); 
        MySqlDataReader Reader = cmd_getAge.ExecuteReader();
        if (Reader.HasRows)
        {
            try
            {
                while (Reader.Read())
                {
                    Age = Reader.GetString(0);
                }
            }
            finally
            {
                Reader.Close();
                con.conclose();
            }
        }
        return Age;
    }

VS返回结果只是“年龄”,也没有错误。

如果相关,我在Windows 7上使用Visual Studio Ultimate 2013.

3 个答案:

答案 0 :(得分:1)

问题是您正在选择特定值“年龄”。如果删除Age附近的引号,则会选择列的值。

public string getAge(string Name) 
    {
        connection con = new connection(); //The object for the class with the connection string 
        con.conopen(); //opens the connection
        string Age = "";
        MySqlCommand cmd_getAge = new MySqlCommand("Select Age from profile where Name = '" + Name + "';", con.con); 
        MySqlDataReader Reader = cmd_getAge.ExecuteReader();
        if (Reader.HasRows)
        {
            try
            {
                while (Reader.Read())
                {
                    Age = Reader.GetString(0);
                }
            }
            finally
            {
                Reader.Close();
                con.conclose();
            }
        }
        return Age;
    }

答案 1 :(得分:1)

评论中的解释:

//why on earth would you ever return an Age as a string!?
public int getAge(string Name) 
{
    //Notice the placeholder in the string. This is important.
    string sql = "Select Age from profile where Name = @Name ;";

    //I see you have your own connection class. However, you used it wrong.
    //If you can't wrap your connection in a using block or try/finally block
    // you're potentially leaving connections hanging open.
    // Do that enough, and you'll lock yourself out of your database.
    //Better just to provide the connection string as a property
    using (var cn = new MySqlConnection("connection string here"))
    using (var cmd = new MySqlCommand(sql, cn))
    { 
        //use the actual db type and length here
        // this parameter makes your code safe from sql injection attacks
        // without the parameter, you're practically begging to get hacked.
        cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = Name;  

        cn.Open();          
        using (var reader = cmd.ExecuteReader())
        {
            //no need to ever check HasRows. 
            //If HasRows would return false, so will reader.Read(), and everything still works the same
            if (reader.Read())
            {
                //surely you're not storing this information in the database as a string!?
                // that would be awful.
                // Age should be an integer.
                // More than that, you should be storing a date, and then calculate the age on retrieval
                DateTime origin = Reader.GetDateTime(0);
                int Age = DateTime.Today.Year - origin.Year;
                if (origin > today.AddYears(-Age)) Age--;
                return Age;
            }
        }
    }
    return 0; //or throw an exception here
}

因为这些评论很长,所以这里是简洁的版本:

public int getAge(string Name) 
{
    string sql = "Select Age from profile where Name = @Name ;";

    using (var cn = new MySqlConnection("connection string here"))
    using (var cmd = new MySqlCommand(sql, cn))
    { 
        cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = Name;  

        cn.Open();          
        using (var reader = cmd.ExecuteReader())
        {
            if (reader.Read())
            {
                DateTime origin = Reader.GetDateTime(0);
                //calculate the age
                int Age = DateTime.Today.Year - origin.Year;
                if (origin > today.AddYears(-Age)) Age--;
                return Age;
            }
        }
    }
    return 0; //or throw an exception here
}

答案 2 :(得分:1)

谢谢大家的帮助!它现在有效:D Andrew Walters和Joel Coehoorn都是对的。对于那些有同样问题的人,我发布了完成的方法。这只是Joel Coehoorn的代码,有一些修复。

public int getAge_Test(string Name)
{
string sql = "Select Age from profile where Name = @Name ;";
  using (var con = new MySqlConnection("server=127.0.0.1;user id=root;persistsecurityinfo=True;database=social_media"))
        using (var cmd = new MySqlCommand(sql, con))
        {
            cmd.Parameters.Add("@Name", MySqlDbType.VarChar, 50).Value = Name; //MySQL has no defintion for SqldbType and also Nvarchar

            con.Open();
            using (var reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                    DateTime origin = reader.GetDateTime(0);
                    //calculate the age
                    int Age = DateTime.Today.Year - origin.Year;
                    if (origin > DateTime.Today.AddYears(-Age)) Age--; //Visual Studio also does not know "today", just "DateTime.Today"
                    return Age;
                }
            }
        }
        return 0; //or throw an exception here
    }