在只有 user_name 的情况下检索 ID

Retrieving ID while having only user_name

我正在尝试做一个私信系统。

到目前为止我有什么。 - 检查玩家是否存在文本框中的名称,如果不存在,则会出现错误。

现在,我正在尝试将其插入 table。问题是 table 有 2 列

to_user_id
from_user_id

因为我使用文本框输入用户名,所以我不知道如何在只有名字的情况下从用户 table 检索 to_user_id。

这是我的代码

      SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());
    conn.Open();
    SqlCommand cmdd = new SqlCommand();
    cmdd.CommandText = "select * from [users]";
    cmdd.Connection = conn;

    SqlDataReader rd = cmdd.ExecuteReader();


    while (rd.Read())
    {
        if (rd[1].ToString() == TextBox_To.Text)
        {
            flag = false;
            break;
        }

    }
    conn.Close();
    if (flag == true)
    {
        Label1.Visible = true;
        Label1.Text = "User does not exist";

    }
    else if(flag == false)
    {

        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString()))
        {
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = con;

            cmd.CommandText = @"INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date) 
                                VALUES (@title, @content, @to, @from, @date)";

            cmd.Parameters.AddWithValue("@title", TextBox_Title.Text);
            cmd.Parameters.AddWithValue("@content", TextBox_Msg.Text.Replace("\n", "<br/>"));
            cmd.Parameters.AddWithValue("@to", TextBox_To.Text);
            cmd.Parameters.AddWithValue("@date", DateTime.Now);
            cmd.Parameters.AddWithValue("@from", Session["id"].ToString());




            con.Open();
            cmd.ExecuteNonQuery();

        }

    }

我当然出错了

Conversion failed when converting the nvarchar value 'username' to data type int.

@编辑,

@cordan 我试过了

DECLARE @user_id = (SELECT id FROM users WHERE user_login=@to ); 
                                    INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date) 
                                    VALUES (@title, @content, @user_id, @from, @date); 
                cmd.Parameters.AddWithValue("@to", TextBox_To.Text);

收到此错误

 Incorrect syntax near '='.
Must declare the scalar variable "@user_id".

这里的这一点是一个巨大的 NO!

SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;

SqlDataReader rd = cmdd.ExecuteReader();


while (rd.Read())
{
    if (rd[1].ToString() == TextBox_To.Text)
    {
        flag = false;
        break;
    }

}
conn.Close();

您正在从用户 table 中选择每个用户,只是为了确定您要查找的用户是否存在。

除了您几乎肯定可以添加的事实之外:

    if (rd[1].ToString() == TextBox_To.Text)
    {
        foundUserId = (int)rd[0]; // I'm assuming the first column in users is the Id - it probably is
        flag = false;
        break;
    }

不要那样做!!


相反,您应该只查找您感兴趣的用户名

SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select top 1 Id from [users] where username=@username";
cmdd.Parameters.AddWithValue("@username",username);
cmdd.Connection = conn;

SqlDataReader rd = cmdd.ExecuteReader();

var userId = 0;
if(rd.Read())
{
    userId = (int)rd[0];
}
conn.Close();
if (userId == 0)
{
    Label1.Visible = true;
    Label1.Text = "User does not exist";
    return;
}
else
   .... // userId holds the users Id
   ...
   cmd.Parameters.AddWithValue("@to", userId);