仅具有user_name时检索ID

时间:2016-05-16 08:55:16

标签: c# sql asp.net sql-server webforms

我正在尝试制作私人讯息系统。

到目前为止我有什么。 - 检查玩家是否存在来自文本框的名称,如果没有,则显示错误。

现在,我正在尝试将其插入表中。问题是该表有2个列

to_user_id
from_user_id

因为我正在使用文本框输入用户名,我不知道如何从用户表中检索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.

@edit,

@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".

1 个答案:

答案 0 :(得分:1)

这里有一个巨大的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();

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

除了你几乎可以肯定只是添加:

    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);