我当前正在编写一种应该从用户中选择* FROM的方法,这样我可以获取用户ID,然后使用该用户ID并在带有注释文本的注释中使用它。这将被插入到名为Comment的自己的数据库表中。代码很乱,我想知道是否无论如何都可以通过会话获取用户ID,这更简单。在这里,我不得不编写大量的代码。
public void CreateComment(TextBox a, TextBox b)
{
HttpContext context = HttpContext.Current;
string username = context.Session["username"].ToString();
string password = context.Session["password"].ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ForumDatabaseConnectionString"].ConnectionString);
SqlCommand cmd1 = new SqlCommand("Select * From Users Where username=@username and password=@password", conn);
cmd1.Parameters.AddWithValue("@username", username);
cmd1.Parameters.AddWithValue("@password", password);
SqlDataAdapter sda = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Open();
string commentId = a.Text; // Kan droppe id om vi skal ha autoincrement.
string commentText = b.Text;
string userId = dt.Rows[0][0].ToString();
string time = DateTime.Now.ToShortDateString();
// MÅ FÅ KOMMENTARENE TIL Å HØRE TIL EN TOPIC!
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ForumDatabaseConnectionString"].ConnectionString);
con.Open();
string sql = "INSERT INTO Comment(commentid, commenttext, userid, time) VALUES(@param1,@param2, @param3, @param4)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@param1", commentId);
cmd.Parameters.AddWithValue("@param2", commentText);
cmd.Parameters.AddWithValue("@param3", userId);
cmd.Parameters.AddWithValue("@param4", time);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}