如何从C#MySQL查询中提取单个列数据?

时间:2012-11-08 23:38:35

标签: c# mysql

如何从用户行中提取列数据? EX:当客户端登录时,在我的WCF服务器上调用它。它适用于var xx = ds.Tables [0] .Rows [1];它在客户端抛出错误的地方。基本上我试图在数据库中验证用户/通行证。然后向客户返回订阅到期时的日期时间。

public bool Authenticate(string userId, string password, out string token)
    {
        token = "";

        string MyConnectionString = "Server=localhost;Database=testdb;Uid=root;Pwd=admin;";
        MySqlConnection sqlCon = new MySqlConnection(MyConnectionString);
        sqlCon.Open();

        MySqlCommand cmd = sqlCon.CreateCommand();
        cmd.CommandText = "SELECT * FROM table1 WHERE username = '"+userId+"' AND password = '"+password+"'";
        MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adap.Fill(ds);


        if (ds.Tables[0].Rows.Count > 0)
        {
            token = Guid.NewGuid().ToString();
            var xx = ds.Tables[0].Rows[0];


            CustomDataSource.AddUserData(token, userId);

            return true;
        }

        return false;
    }

2 个答案:

答案 0 :(得分:0)

var xx = ds.Tables [0] .Rows [0] .ItemArray [5];

是怎么回事。

答案 1 :(得分:0)

尝试使用foreach循环

foreach (DataRow row in ds.Tables[0].Rows) 
{
    var xx = row[1];
    var x = row[5];

    // other codes

    return true;
}

还有一件事,参数化您的查询以避免SQL injection

using(MySqlConnection sqlCon = new MySqlConnection(MyConnectionString))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        cmd.Connection = sqlCon;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT * FROM table1 WHERE username = @user AND password = @pass";
        cmd.Parameters.AddWithValue("@user", userId);
        cmd.Parameters.AddWithValue("@pass", password);
        using (MySqlDataAdapter adap = new MySqlDataAdapter(cmd))
        {
            try
            {
                DataSet ds = new DataSet();
                adap.Fill(ds);
            }
            catch (MySqlException e)
            {
                // do something with the exception
                // don't hide it!
            }
        }
    }
}