sql语法错误,以及与sql语法相关的字符串问题

时间:2011-03-30 17:12:18

标签: c# asp.net mysql sql html

当我在下面的代码中将idWallPosting添加到我的select语句时,嘿家伙得到sqlsyntax错误:

using (OdbcCommand cmd = new OdbcCommand("SELECT idWallPosting, wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN User u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE wp.UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
    {
        using (OdbcDataReader reader = cmd.ExecuteReader())
        {
            test1.Controls.Clear();

            while (reader.Read())
            {

                System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                div.Attributes["class"] = "test";


                div.ID = String.Format("{0}", reader.GetString(2));
                // this line is responsible, problem here and my sqlsntax, im trying to set the SELECT idWallPosting for the div ID
                Image img = new Image();
                img.ImageUrl = String.Format("{0}", reader.GetString(1));

                img.AlternateText = "Test image";

                div.Controls.Add(img);
                div.Controls.Add(ParseControl(String.Format("&nbsp&nbsp " + "{0}", reader.GetString(0))));
                div.Attributes.Add("onclick", "return confirm_delete();");

                div.Style["clear"] = "both";
                test1.Controls.Add(div);

            }
        }
    }

我的数据库看起来像这样:

enter image description here

在我的代码中我试图将div.ID设置为我的WallPosting表中的当前idWallPosting,所以我也不确定我是否也正确。

修改

错误:

  

无法将'System.Int32'类型的对象强制转换为'System.String'。

与此相关,我认为:

div.ID = String.Format("{0}", reader.GetString(2));

2 个答案:

答案 0 :(得分:1)

你需要一个逗号。这样:

using (OdbcCommand cmd = new OdbcCommand("SELECT idWallPosting wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN User u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE wp.UserID=" + userId + " ORDER BY idWallPosting DESC", cn))

应该是这样的:

using (OdbcCommand cmd = new OdbcCommand("SELECT idWallPosting, wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN User u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE wp.UserID=" + userId + " ORDER BY idWallPosting DESC", cn))

逗号:--------------------------------------------- -------------------------------------------------- ----- ^

编辑:

您可以尝试GetValue而不是GetString。 GetValue的描述:

  

以原始格式获取指定序号的列的值。

答案 1 :(得分:0)

wallPosting是一个int,你正在使用.GetString。你可能应该使用.GetInt32。