如何从mysql中读取一行?

时间:2015-12-28 16:58:18

标签: c# mysql row

我有mysql中的用户配置文件,我想读取一行(某些用户)并将值添加到对象" user"

以下是我的代码的一部分:(返回用户的函数)

connection.Open();

person person_1 = new person();

//1. Read name
string sql = "select name from profili where name=@name and surname=@surname";
    cmd = new MySqlCommand(sql, konekcija);
    cmd.Parameters.Add("@name", name);
   cmd.Parameters.Add("@surname", surname);

MySqlDataReader reader = cmd.ExecuteReader();

if (reader.Read()) {

  person_1.name = reader["name"].ToString();


//2. Read surname
string sql = "select surname from profili where name=@name and surname=@surname";
cmd = new MySqlCommand(sql, konekcija);
cmd.Parameters.Add("@name", name);
   cmd.Parameters.Add("@surname", surname);
    person_1.surname = reader["surname"].ToString();
return person_1;

有了这个我只得到名字,姓氏为空(见debbuger中)

1 个答案:

答案 0 :(得分:1)

你的代码毫无意义。您已经知道姓氏和名称,因为您将它们作为WHERE条件的参数传递。从中可以看出,surname为null的问题是你不执行第二个命令。

你应该添加

//2. Read surname
string sql = "select surname from profili where name=@name and surname=@surname";
cmd = new MySqlCommand(sql, konekcija);
cmd.Parameters.Add("@name", MySqlType.VarChar).Value = name;
cmd.Parameters.Add("@surname", MySqlType.VarChar).Value = surname;
reader = cmd.ExecuteReader();
person_1.surname = reader["surname"].ToString();

说,执行命令两次以检索单行是没有意义的。您的查询文本可以轻松添加您要检索的所有列名,并只执行一次读取

//1. Read the row matching the known surname and name 
string sql = @"select name, surname, column1, column2, colx 
              from profili where name=@name and surname=@surname";

cmd = new MySqlCommand(sql, konekcija);
cmd.Parameters.Add("@name", MySqlType.VarChar).Value = name;
cmd.Parameters.Add("@surname", MySqlType.VarChar).Value = surname;
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read()) {
   person_1.name = reader["name"].ToString();
   person_1.surname = reader["surname"].ToString();
   person_1.Property1 = reader["column1"].ToString();
   ...and so on for other columns