获取一列并将值转换为int

时间:2014-05-18 16:32:02

标签: asp.net sql sql-server

public int AuthenticatedUserAge(String User_name)
{
    string sql = "SELECT UserName,Age FROM tblDataProg WHERE (UserName ='" + User_name + "')";
    ds = GetDataSet(sql);

    int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());

    return help;
}

我无法理解为什么这行不会将年龄转换为int类型并返回一个值:

int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());

3 个答案:

答案 0 :(得分:1)

这个问题完全脱离了主题,但我认为值得一提。请不要通过连接字符串来创建SQL语句。这会产生SQL Injection攻击可能性。而是考虑SqlParameter类并使用这些参数组合WHERE谓词。

在这里你得到nice example(特别注意方便的AddWithValue方法)。

谢谢!

答案 1 :(得分:0)

更多地测试你的假设。您假设GetDataSet返回一行但可能不是: -

int help = 0;

if (ds.Tables[0].Rows.Count == 0)
{
    throw new ApplicationException("no rows were returned, here is an error to deal with");
}
else if (ds.Tables[0].Rows[0]["Age"] == System.DbNull.Value)
{
    throw new ApplicationException("a row was found but Age is null, here is an error to deal with");
}
else
{
    help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
}

答案 2 :(得分:0)

int help;

int.TryParse(Convert.ToString(ds.Tables [0] .Rows [0] [“Age”]),out help);

并查看调试模式下的代码