简体   繁体   中英

SQL Exception Unhanded Code in ASp.net C#

I was doing my ASP.Net project for my academic purpose and i am trying to retrieve an image stored in Database as binary to a grid view. And i am getting this error.

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'.

And the keyword 'in' is coming from my session email = admin@test.in

So here is my entire code in asp c#, the default page , mypets.aspx.cs

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;
    }
}

}

Regarding Your Error Message

Incorrect syntax near the keyword 'in'.

This comes as a result of your actual e-mail address containing the word IN which is a keyword within SQL. Since you aren't using parameterziation or wrapping the value in quotes, SQL thinks you are trying to perform an IN query and blows up.

Parameterization, Not Concatenation

You really should be using parameterization to handle this as opposed to string concatenation for all of your queries, as it can not only leave you vulnerable to nastiness like SQL Injection, but it can help avoid issues with query syntax :

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

and :

SqlCommand cmd = new SqlCommand("SELECT pic FROM pets WHERE imageid= @image", con);
cmd.Parameters.AddWithValue("@image",imageid);
// Execute here

if it is indeed the in, in the email, you could try to change it to this:

cmd.CommandText = "select [imageid], [petname],[petsdis],[catgry] from [pets] where [email]='" + email + "'";

for added security you should probably replace all ' characters with \\' in email (though it is probably not necessary

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM