从数据库中检索数据到C#中的标签

时间:2017-09-22 17:03:44

标签: c# sql sql-server

List Of Errors are Here 我已经使用此代码从我的数据库中检索数据,但是当我运行它时,标签不会显示用户的名称。我也试图从其他形式获取数据,但仍然保持不变。

代码有问题吗?谢谢..

  SqlConnection _sqlcnn = new SqlConnection("Data Source=MELIODAS;Initial Catalog=PROJECT;Integrated Security=True");    //SQL Connection Established
        _sqlcnn.Open();
        try
        {
            SqlDataReader _reader = null;
            SqlCommand _cmd = new SqlCommand("select FNAME from LOGINFORM where Username=@USERNAME", _sqlcnn);

            SqlParameter _param = new SqlParameter();
            _cmd.Parameters.AddWithValue("@USERNAME", "_FNAME");
            _param.ParameterName = "@USERNAME";
            _param.Value = _FNAME;
            _cmd.Parameters.Add(_param);

            _reader = _cmd.ExecuteReader();         //for displaying users name in the label
            if (_reader.Read())
            {
                _lblname.Text = _reader.GetString(0);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

2 个答案:

答案 0 :(得分:1)

1)您为sql命令声明了参数@USERNAME,但没有传递此参数:

SqlCommand _cmd = new SqlCommand("select FNAME from LOGINFORM where Username=@USERNAME", _sqlcnn);

// add username parameter value
// assuming _FNAME is the username you want to pass
_cmd.Parameters.AddWithValue("@USERNAME", _FNAME);

2)您没有从SqlDataReader

中读取值
_reader = _cmd.ExecuteReader();
if (_reader.Read())
    _lblname.Text = _reader.GetString(0); // read db value

我只使用if代替while,因为您似乎只对第一行(可能是单行)感兴趣。

答案 1 :(得分:0)

请将参数@USERNAME添加到命令中:

try {
        assert document != null;
        document.putProperties(properties);
        if(photos.size()>0) {
            String pName;
            for(int i=0;i<photos.size();i++){
                pName = photos.get(i);
                UnsavedRevision newRev = document.getCurrentRevision().createRevision();
                newRev.setAttachment(pName + ".png", "image/png", getphotoFromStorage(pName));
                newRev.save();
            }

        }
    } catch (CouchbaseLiteException e) {
        e.printStackTrace();
        Toast toast = Toast.makeText(getApplicationContext(),
                "Save Failed" + e, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }