-3
  SqlCommand cmd1 = new SqlCommand("select usr_name,usr_surname,usr_passwd,usr_sorumluluk_kod from ZRR_Users where usr_id='" + Session["user_id"] + "'", conn);
            conn.Open();//conenction open
            SqlDataReader dr = cmd1.ExecuteReader();
            cmd1.Parameters.AddWithValue("@user_id", Session["usr_id"].ToString());
            dr.Read();

                txtname.Text = dr["usr_name"].ToString();
                txtsurname.Text = dr["usr_surname"].ToString();
                txtpasswd.Text = dr["usr_passwd"].ToString();
                txtSorKodu.Text = dr["usr_sorumluluk_kod"].ToString();



            conn.Close();//conenction close
4

3 回答 3

1

把从数据库返回的列名放在“ColumnName”所在的位置。如果是字符串,可以使用 .ToString()。如果是其他类型,则需要使用 System.Convert 进行转换。

SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
     txtname.Text = dr["usr_name"].ToString();
     txtsurname.Text = dr["usr_surname"].ToString();
     txtpasswd.Text = dr["usr_passwd"].ToString();
     txtSorKodu.Text = dr["usr_sorumluluk_kod"].ToString();
}
于 2013-08-02T12:26:48.880 回答
1
  1. 您必须在调用之前提供 sql 参数SqlCommand.ExecuteReader
  2. sql 参数名称必须是 sql 查询的一部分 ( usr_id=@userID)
  3. 您必须将会话值转换为正确的数据类型(例如(int)Session["user_id"]

string sql = @"select usr_name,usr_surname,usr_passwd,usr_sorumluluk_kod 
               from ZRR_Users 
               where usr_id=@userID";
using(var conn=new SqlConnection("Your Connection-String"))
using (var cmd1 = new SqlCommand(sql, conn))
{
    conn.Open(); 
    cmd1.Parameters.AddWithValue("@userID", (int)Session["user_id"]); // cast to the correct datatype
    using (var dr = cmd1.ExecuteReader())
    {
        if (dr.Read())
        {
            txtname.Text = dr.GetString(dr.GetOrdinal("usr_name"));
            txtsurname.Text = dr.GetString(dr.GetOrdinal("usr_surname"));
            txtpasswd.Text = dr.GetString(dr.GetOrdinal("usr_passwd"));
            txtSorKodu.Text = dr.GetString(dr.GetOrdinal("usr_sorumluluk_kod"));
        }
    }
}
于 2013-08-02T12:22:04.863 回答
0

尝试这个

using(var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Default"].ToString()))
            {

                string sqlString = "select usr_name,usr_surname,usr_passwd,usr_sorumluluk_kod from ZRR_Users where usr_id=@userID";

                var sqlCommand = new SqlCommand(sqlString, sqlConnection);
                sqlCommand.Connection.Open();

                var reader = sqlCommand.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read()) 
                    {

                        txtname.Text = reader.GetString(0)
                        txtsurname.Text = reader.GetString(1);
                        txtpasswd.Text = reader.GetString(2);
                        txtSorKodu.Text = reader.GetString(3);
                     }
                }
        }
于 2013-08-02T12:27:19.057 回答