asp.net C# 根据传递的查询字符串从 SQL 检索数据

本文关键字:字符串 查询 SQL 数据 检索 net asp | 更新日期: 2023-09-27 18:34:19

假设 cardDetailsID 为 5。

查看数据库的 cardDetails 表中的记录编号 5,可以看到它的其他字段包括 "bgcolor" 和 "borderstyle"。因此,对于这个特定的记录,我得到了cardDetailsID = 5,bgcolor = blue,bordersytle = solid。

我希望能够从 cardDetailsID 中获取 bgcolor 和边框设置(蓝色和纯色)。

这是到目前为止的代码。查询字符串中的值正在工作(正在传递数字"5"),但现在如何获取行的其余设置?

    cardDetailsIDrv.Text = Request.QueryString["cardDetailsID"];
    cardDetailsIDrv.Visible = false;
    //create Connection
    SqlConnection myConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]);

    //create Command
    SqlCommand getCardDetailsCMD = new SqlCommand("SELECT * FROM cardDetails WHERE cardDetailsID =" + Convert.ToInt32(cardDetailsIDrv.Text), myConnection);
    myConnection.Open();
    //create datareader
    SqlDataReader myReader = getCardDetailsCMD.ExecuteReader();
    //code works properly up till here

    try
    {
        //Using DataReader to retrieve info from the database and display it on the panel
        while (myReader.Read())
        { 
           //I'm guessing here is where I'm messing things up
           pnlCardps.BackColor = Color.FromName(myReader["bgcolour"].ToString());
           pnlCardps.BorderStyle = (BorderStyle)Enum.Parse(typeof(BorderStyle), myReader["borderstyle"].ToString());
        }
    }
    finally
    {
        if (myReader != null)
        {
            myReader.Close();
        }
        if (myConnection != null)
        {
            myConnection.Close();
        }
    }

问题解决了!!我所要做的就是将while循环中的代码调整为:

string bgColour = myReader["bgColour"].ToString();
pnlCardrv.BackColor = Color.FromName(bgColour);
string borderColour = myReader["borderColour"].ToString();
pnlCardrv.BorderColor = Color.FromName(borderColour);

asp.net C# 根据传递的查询字符串从 SQL 检索数据

首先,您必须获取通过查询字符串传递的detailsID,然后执行查询。

int id;
if(int.TryParse(Request.QueryString["detailsID"],out id))
{
string sql= string.Format("select .. from .. where id={0}",id);// using SqlParameter is much better and secure
// and execute your query and fetch the data reader
while(reader.Read())
{
 // bla bla bla
}
}

Request.QueryString["detailsID"]将获取查询字符串变量的值。

if (Request.QueryString("detailsID") == null || Request.QueryString("detailsID").Length <= 0 || !int.TryParse(Request.QueryString("detailsID"), out detailsID) || MessageThreadID <= 0)
{
    //This is my standard exception, but you can handle it how you want.
    throw new Exception("Error: unable to load detailsID.  Request.QueryString.count: " + Request.QueryString.Count + " Request.QueryString('"detailsID'"): " + Request.QueryString("detailsID"));
}