C# 无法执行查询-错误:“媒体”附近的语法不正确
此代码显示一个错误: “媒体”附近的语法不正确 这是什么意思?我哪里出错了C# 无法执行查询-错误:“媒体”附近的语法不正确,c#,asp.net,sql-server,nvarchar,C#,Asp.net,Sql Server,Nvarchar,此代码显示一个错误: “媒体”附近的语法不正确 这是什么意思?我哪里出错了 if (!IsPostBack) { if (Request.QueryString["sub"] != null) { SqlDataAdapter da = new SqlDataAdapter( "select * from entry_table Where sub=" + Request.QueryString["sub"], Co
if (!IsPostBack)
{
if (Request.QueryString["sub"] != null)
{
SqlDataAdapter da = new SqlDataAdapter(
"select * from entry_table Where sub=" + Request.QueryString["sub"],
ConfigurationManager.ConnectionStrings["cozmotestConnectionString"].ConnectionString);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Label1.Text = dt.Rows[0]["sub"].ToString();
Label2.Text = dt.Rows[0]["body"].ToString();
}
}
}
<div style=" padding-bottom:10px"><h1><asp:Label Font-Bold="true" ID="Label1" runat="server" Text="Label"></asp:Label></h1></div>
<div><asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div>
既然您标记了您的问题,我假设您的子列是nvarchar
这就是为什么需要对其值使用单引号。喜欢
..sub = '" + Request.QueryString["sub"] + "'"..
但不要用这种方式。
更重要的是,您应该始终使用。这种类型的字符串连接对攻击是开放的
用于处理SqlConnection、SqlCommand和SqlDataAdapter
在where子句中,可能需要在值周围加上单引号
SqlDataAdapter da = new SqlDataAdapter("select * from entry_table Where sub='" + Request.QueryString["sub"] + "'", ConfigurationManager.ConnectionStrings["cozmotestConnectionString"].ConnectionString);
尽管我强烈建议您使用参数化查询来避免SQL注入攻击,但这样做可能会在这个问题上有所帮助
string str = Request.QueryString["sub"];
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cozmotestConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter(
"select * from entry_table Where sub='"+str+"'",con)
//Your remaining parts will come here
请告诉我结果。请求的值是多少。QueryString[sub]到底是多少?子列的类型是什么?选择*from entry_table,其中sub=请,请,请了解我在请求中的想法。QueryString[sub]具有字符串“Media”,因此执行sql查询时很明显存在语法问题,所以更改为select*from entry_table,其中sub='+Request。QueryString[sub]+'。主题列的类型为nvarchar。
string str = Request.QueryString["sub"];
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cozmotestConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter(
"select * from entry_table Where sub='"+str+"'",con)
//Your remaining parts will come here