-3

我需要从数据库中获取 6 个值并将它们绑定到链接按钮文本她是代码

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //string post = Request.QueryString["post"];
        ////string title = "nokia";

        string date = DateTime.Now.ToShortDateString();
        SqlConnection conn = new SqlConnection(); 

        conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\nokiaoaq\Desktop\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
        try
        {
            conn.Open();
            //string str = "insert into Table1 (title , date_ ,www, cat) values  (' " + TextBox1.Text + "','" + DateTime.Now.ToShortDateString() + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Text + "')";
            ////string str = "INSERT INTO Table1  (title,date_,www ) values ('ddddddd','aaaaaaa','qqqqqq')";


            string str =
                //"SELECT   from table1  WHERE  cat = 1 and datee='" + date + "'ORDER BY datee";
            "SELECT table1.title  FROM table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee DESC";

            SqlCommand objcmd = new SqlCommand(str, conn);
            SqlDataAdapter da1 = new SqlDataAdapter(objcmd);
            DataTable dt = new DataTable();
            da1.Fill(dt);

            //DataRow dr = new DataRow();
            //DataRow dr = ds.Tables[0].Rows[0];

            foreach (DataRow dr in dt.Rows)
            {
                ml1.Text = dr[0].ToString();
                ml2.Text = dr[1].ToString();
                ml3.Text = dr[2].ToString();
                ml4.Text = dr[3].ToString();
                ml5.Text = dr[4].ToString();
                ml6.Text = dr[5].ToString();
            }
        }
        catch (Exception ex)
        {
            Label4.Text = "Failed to connect to data source";
        }
        finally
        {
            conn.Close();
        }
    }
}

ml 是链接按钮 ID

4

1 回答 1

3

您正在尝试将返回的行中的 6 个字段分配给 6 个不同的文本框,但您的选择查询只要求一个字段。如果您希望返回多个字段,请将它们的名称添加到选择查询中(将 fieldX 更改为适当的字段名称)。

string str = "SELECT title, field1, field2, field3, field4, field5  " + 
             "FROM table1 WHERE cat = 1 and datee=@dt ORDER BY datee DESC";

也不要使用字符串连接来构建 sql 语句。始终使用参数化查询

SqlCommand objcmd = new SqlCommand(str, conn);
objcmd.Parameters.AddWithValue("@dt", datee);
.....

这将避免格式化字符串、日期、数字等问题,以及 sql 注入问题。

顺便说一句,我希望您的代码只返回一行,因为就目前而言,如果您返回的行不止一行,那么文本框中只会显示日期最早的那一行。(如果是这种情况,那么 order by 就没用了)。如果返回的行不止一行,则应考虑将数据表绑定到 GridView 以显示返回的所有记录。

于 2013-05-06T13:06:00.853 回答