我正在为我的学术目的而做我的ASP.Net项目,我正在尝试将存储在数据库中的图像作为二进制文件检索到网格视图。我收到了这个错误。
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near the keyword 'in'.
关键字“in”来自我的会话email = admin@test.in
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.IO;
public partial class mypets : System.Web.UI.Page
{
string strCon = ConfigurationManager.ConnectionStrings["petlyConnectionString"].ConnectionString;
DbConnect db = new DbConnect();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
// if (Session["email"] == null)
// {
// Response.Redirect("login.aspx");
// }
string m = Session["email"].ToString();
email.Text = m;
// string sql = "SELECT pic FROM pets WHERE email="+ (string)Session["email"] +"";
// Image img = (Image)FindControl("petimage");
// img.ImageUrl = "sql";
}
private void BindGridviewData()
{
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
string emai = Session["email"].ToString();
cmd.CommandText = "select [imageid], [petname],[petsdis],[catgry] from [pets] where [email]=" + emai+ "";
cmd.Connection = con;
con.Open();
gvImages.DataSource = cmd.ExecuteReader();
gvImages.DataBind();
con.Close();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string cat = catgry.SelectedValue.ToString();
string na = Session["email"].ToString();
if (FileUpload1.HasFile)
{
int length = FileUpload1.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = FileUpload1.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length);
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
using (SqlConnection con = new SqlConnection(strCon))
{
db.con.Open();
// db.cmd = new SqlCommand("update ureg set picture='" + fn + "' where email='" + (string)Session["email"] + "'", db.con);
db.cmd = new SqlCommand("insert into pets(petname,email,catgry,mb,petsdis,pic) values(@PetName,@Email,@Catgry,@Mb,@PetDis,@Image) ", db.con);
db.cmd.Parameters.AddWithValue("@PetName", petname.Text);
db.cmd.Parameters.AddWithValue("@Email", email.Text);
db.cmd.Parameters.AddWithValue("@Catgry", cat);
db.cmd.Parameters.AddWithValue("@Mb", mb);
db.cmd.Parameters.AddWithValue("@PetDis", petsdis.Text);
db.cmd.Parameters.AddWithValue("@Image", imgbyte);
db.cmd.Connection = con;
con.Open();
db.cmd.ExecuteNonQuery();
Response.Write("<script>alert('Pet Details Successfully Added')</script>");
con.Close();
BindGridviewData();
}
}
}
}
mypets.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/akshara.masteAutoEventWireup="true" CodeFile="mypets.aspx.cs" Inherits="mypets" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="padding100">
<div class="container">
<table class=" table-responsive" width="100%">
<tr >
<td width="60%" id="listpets">
<h1 class="common"> Your Pets</h1>
<asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="False" AllowPaging="True" >
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Pet ID" InsertVisible="False" />
<asp:BoundField ItemStyle-Width="150px" DataField="petname" HeaderText="Pet Name" SortExpression="petname" />
<asp:BoundField ItemStyle-Width="150px" DataField="petsdis" HeaderText="Discription" SortExpression="petsdis" />
<asp:BoundField ItemStyle-Width="150px" DataField="catgry" HeaderText="Category" SortExpression="catgry" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("imageid") %>'Height="150px" Width="150px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
<div class="clearfix"></div>
<td width ="40%" id="addpets">
<h1 class="common"> Add Your Pets</h1>
<div class="panel-body">
<div id="signupform" class="form-horizontal" role="form">
<div class="form-group">
<label for="email" class="col-md-3 control-label">Email</label>
<div class="col-md-9">
<asp:TextBox runat="server" ID="email" CssClass="form-control" placeholder="Email Address" ReadOnly="True"></asp:TextBox>
</div>
</div>
<div class="form-group">
<label for="petname" class="col-md-3 control-label">
Pets Name</label>
<div class="col-md-9">
<asp:TextBox runat="server" ID="petname" CssClass="form-control" placeholder="Name"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" ForeColor="Red" ControlToValidate="petname" runat="server" ErrorMessage="Field cannot be blank"></asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<label for="catagry" class="col-md-3 control-label">
Category</label>
<div class="col-md-9">
<asp:DropDownList ID="catgry" AppendDataBoundItems="true" runat="server" CssClass="btn btn-default dropdown-toggle" >
<asp:ListItem Text="DOG" Value="Dog" />
<asp:ListItem Text=" -- Beagle" Value="Beagle" />
<asp:ListItem Text=" -- Boxer" Value="Boxer" />
<asp:ListItem Text=" -- Bulldog" Value=" Bulldog" />
<asp:ListItem Text=" -- Cocker Spaniel" Value="Cocker Spaniel" />
<asp:ListItem Text=" -- Dalmatian" Value=" Dalmatian" />
<asp:ListItem Text=" -- Doberman" Value=" Doberman" />
<asp:ListItem Text=" -- German Shepherd" Value=" German Shepherd " />
<asp:ListItem Text=" -- Golden Retriever" Value=" Golden Retriever " />
<asp:ListItem Text=" -- Husky" Value=" Husky" />
<asp:ListItem Text=" -- Labrador" Value="Labrador " />
<asp:ListItem Text=" -- Mastiff" Value=" Mastiff " />
<asp:ListItem Text=" -- Pomeranian" Value=" Pomeranian " />
<asp:ListItem Text=" -- Pug" Value="Pug " />
<asp:ListItem Text=" -- Rottweiler" Value="Rottweiler " />
<asp:ListItem Text=" -- Saint Bernard" Value="Saint Bernard " />
<asp:ListItem Text=" -- Other Breeds" Value="Other Breeds " />
<asp:ListItem Text="BIRDS" Value="Birds" />
<asp:ListItem Text="CATS" Value="Cats" />
<asp:ListItem Text=" -- Birman" Value="Birman" />
<asp:ListItem Text=" -- British Shorthair" Value="British Shorthair" />
<asp:ListItem Text=" -- Oriental" Value="Oriental" />
<asp:ListItem Text=" -- Persian" Value="Persian" />
<asp:ListItem Text=" -- Ragdoll" Value="Ragdoll" />
<asp:ListItem Text=" -- Russian Blue" Value="Russian Blue" />
<asp:ListItem Text=" -- Siberian" Value="Siberian" />
<asp:ListItem Text=" -- Sphynx" Value="Sphynx" />
<asp:ListItem Text=" -- Other Cat Breeds" Value="Other Cat Breeds" />
<asp:ListItem Text="OTHER PETS" Value="other pets" />
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ForeColor="Red" ControlToValidate="catgry" runat="server" ErrorMessage="Field cannot be blank"> </asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<label for="petsdis" class="col-md-3 control-label">
Discription</label>
<div class="col-md-9">
<asp:TextBox runat="server" ID="petsdis" CssClass="form-control" placeholder="Discription" TextMode="MultiLine"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" ForeColor="Red" ControlToValidate="petsdis" runat="server" ErrorMessage="Field cannot be blank"></asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<label for="mobile" class="col-md-3 control-label">
Owners Mobile No.</label>
<div class="col-md-9">
<asp:TextBox runat="server" ID="mb" CssClass="form-control" placeholder="Enter your 10 digit number" TextMode="SingleLine"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ForeColor="Red" ControlToValidate="mb" runat="server" ErrorMessage="Field cannot be blank"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="mobile" runat="server" ErrorMessage="Mobile Number Invalid" ValidationExpression="^[7-9][0-9](\s){0,1}(\-){0,1}(\s){0,1}[0-9]{1}[0-9]{7}$" ControlToValidate="mb"></asp:RegularExpressionValidator>
</div>
<div class="col-md-9">
<asp:Label ID="upl" runat="server" Text="Upload Photo" CssClass="form-control"></asp:Label> <asp:FileUpload ID="FileUpload1" runat="server" CssClass="fa-upload" />
</div>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-3 col-md-9">
<asp:Button ID="Button2" runat="server" Text="Add My Pet" CssClass="btn btn-success" OnClick="Button1_Click" />
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
</table>
</div>
</div>
</asp:Content>
ImageHandler.ashx
<%@ WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
public class ImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string imageid = context.Request.QueryString["ImID"];
string strCon = ConfigurationManager.ConnectionStrings["petlyConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strCon);
con.Open();
SqlCommand cmd = new SqlCommand("select pic from pets where imageid=" + imageid, con);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr[0]);
con.Close();
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
答案 0 :(得分:2)
关于您的错误消息
关键字&#39;在&#39;附近的语法不正确。
这是因为您的实际电子邮件地址包含单词IN
,这是SQL中的关键字。由于您没有使用parameterziation或将值包装在引号中,因此SQL认为您正在尝试执行IN
查询并将其炸毁。
参数化,非连接
你真的应该使用参数化来处理这个问题而不是所有查询的字符串连接,因为它不仅会让你容易受到像SQL注入这样的肮脏,而且它可以帮助避免查询语法问题:
cmd.CommandText = "SELECT [imageid], [petname], [petsdis], [catgry] FROM [pets] WHERE [email]= @email";
// Add your parameter
cmd.Parameters.AddWithValue("@email",Convert.ToString(Session["email"]));
// Execute here
和:
SqlCommand cmd = new SqlCommand("SELECT pic FROM pets WHERE imageid= @image", con);
cmd.Parameters.AddWithValue("@image",imageid);
// Execute here
答案 1 :(得分:-1)
如果确实是in,在电子邮件中,您可以尝试将其更改为:
cmd.CommandText = "select [imageid], [petname],[petsdis],[catgry] from [pets] where [email]='" + email + "'";
为了增加安全性,你应该用电子邮件替换所有''字符'(尽管可能没有必要
)