Solved

"Data type mismatch in criteria expression" SQL UPDATE statement fails

Posted on 2006-11-15
8
1,336 Views
Last Modified: 2011-09-20
I am using an access database for a very small C# ASP.NET site.  I am trying to perform an update on a record using a parameterized UPDATE statement, but get an error when it is executed. The code is listed below:

        string ID = Request.QueryString["ID"];

        DateTime tempdate = _Date.SelectedDate;
        int hr = Convert.ToInt32(hour.Text);
        if (ampm.SelectedValue == "PM")
            hr += 12;
        int min = Convert.ToInt32(minute.Text);
        DateTime datetime = new DateTime(tempdate.Year, tempdate.Month, tempdate.Day, hr, min, 0);

        if (!Page.IsValid)
            return;

        OleDbCommand cmd = new OleDbCommand("UPDATE tbl_calendar "
            + "SET _Date = @datetime, Title = @title, Type = @typeGroup, Audience = @audience, "
            + "PersonResponsible = @pResponsible, Location = @location, Description = @description "
            + "WHERE ID = @ID", conn);
           
        cmd.Parameters.AddWithValue("@datetime", datetime.ToString());
        cmd.Parameters.AddWithValue("@title", eTitle.Text);
        cmd.Parameters.AddWithValue("@audience", Audience.Text);
        cmd.Parameters.AddWithValue("@typeGroup", _Type.SelectedItem.Value);
        cmd.Parameters.AddWithValue("@pResponsible", PResponsible.Text);
        cmd.Parameters.AddWithValue("@location", location.Text);
        cmd.Parameters.AddWithValue("@description", description.Text);
        cmd.Parameters.AddWithValue("@ID", ID);

        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();

Also if I remove the parameter for _Date so it looks like "...SET _Date = '" + datetime + "',..."  The code executes, but then the changes aren't reflected.

On another note, I have an INSERT statement that formats 'datetime' the exact same way, but with a parameter, and it works.  Your help is very much appreciated.

Thank you,

Phil
0
Comment
Question by:klog_69
  • 4
  • 3
8 Comments
 
LVL 6

Expert Comment

by:DonKyles
ID: 17953071
try this

from
cmd.Parameters.AddWithValue("@datetime", datetime.ToString());
to
cmd.Parameters.AddWithValue("@datetime", datetime.ToShortDateString());
0
 

Author Comment

by:klog_69
ID: 17953243
DonKyles,

Thanks for the quick response, but this does not help.
0
 

Author Comment

by:klog_69
ID: 17953310
I'm not exactly sure what I did, but I removed the Audience field because I don't actually need it.  The Audience part was giving be the same error.  My only thought is that with parameters, you have to keep your items in the same order that they are in in the table.  So now everything works, however if I move the _Date field after the title field I get the mismatch error error again. Can anyone confirm that this is indeed what is happening?

Thank you,

Phil
0
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
LVL 6

Accepted Solution

by:
DonKyles earned 125 total points
ID: 17958887
By doing your way, you have to make the parameter in the same order that you declare in the SQL statement not the database table

OleDbCommand cmd = new OleDbCommand("UPDATE tbl_calendar "
            + "SET _Date = @datetime, Title = @title, Type = @typeGroup, Audience = @audience, "
            + "PersonResponsible = @pResponsible, Location = @location, Description = @description "
            + "WHERE ID = @ID", conn);
           
        cmd.Parameters.AddWithValue("@datetime", datetime.ToString());
        cmd.Parameters.AddWithValue("@title", eTitle.Text);
        cmd.Parameters.AddWithValue("@audience", Audience.Text);
        cmd.Parameters.AddWithValue("@typeGroup", _Type.SelectedItem.Value);
        cmd.Parameters.AddWithValue("@pResponsible", PResponsible.Text);
        cmd.Parameters.AddWithValue("@location", location.Text);
        cmd.Parameters.AddWithValue("@description", description.Text);
        cmd.Parameters.AddWithValue("@ID", ID);

there is another way to do this by writeing the SQL frist
qry = "UPDATE tbl_calendar " +
         "SET _Date = '" + datetime.ToString() + "',  " +
         "       Title = '" + eTitle.Text + "', " +
         "       Type = '" + _Type.SelectedValue+ "', " +
         "       Audience = '" + Audience.Text.Replace("'", "''") + "', " +
         "       PersonResponsible = '" + PResponsible.Text.Replace("'", "''") + "', " +
         "       Location = '" + location.Text.Replace("'", "''") + "', " +
         "       Description = '" + description.Text.Replace("'', "''") + "  " +
         "WHERE ID = '" + ID + "'";

// you can print out the qry frist to see the complete query before you execute it
//                             lblSql.Text = qry;

OleDbCommand cmd = new OleDbCommand(qry, conn);   ..... and so on
0
 

Author Comment

by:klog_69
ID: 17962364
Thanks for the clarification.  I had essentially what you are talking about with the alternative you presented, but I ran into the problem of single apostrophes.  So in researching this problem I saw the replace method first, and then stumbled onto my current solution, which I like better.  I feel it is far easier to determine what is going on in the sql statement.  Thank you for your input though.

Phil
0
 
LVL 6

Expert Comment

by:DonKyles
ID: 17962666
Different programmers use different way to write/run the code.

This another way to do it

string[] credentials =  { datetime.ToString(), eTitle.Text, _Type.SelectedValue,  Audience.Text, PResponsible.Text,  location.Text, description.Text, ID  };

string cmdText = "UPDATE tbl_calendar " +
                          "SET _Date = '" + credentials[0]  + "',  " +
                          "       Title = '" + credentials[1] + "', " +
                          "       Type = '" + credentials[2] + "', " +
                          "       Audience = '" + credentials[3]  + "', " +
                          "       PersonResponsible = '" + credentials[4] + "', " +
                          "       Location = '" + credentials[5]  + "', " +
                          "       Description = '" + credentials[6]  + "  " +
                          "WHERE ID = '" + credentials[7] + "'";

SqlConnection connection = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(cmdText, conn);
try
{
       conn.Open();
       cmd.ExecuteNonQuery();
       conn.Close();
}
catch (Exception ex)
{
       lblErrorMessage.Text = ex.message;
}

Just stick into the way you like and easy for you to debug and find the problem.

My style would be..
- Create SQL statement and print out to the screen (I can see the actual value from the web from)
- Run the SQL Stagement in Query Analysis (try different input from the web form)
- SQL statement execute successfully then I go to the code part  and write the execute command

Hope this is helpful
0
 
LVL 49

Expert Comment

by:Gustav Brock
ID: 17974359
The order of parameters is of no importance.
I think your problem is the syntax for datetime string values in JET SQL:

  "SET _Date = '" + datetime.ToString() + "',  " +

It should be:

  "SET _Date = #" + datetime.ToString() + "#,  " +

and the string must be in US format, m/d/yyyy, or ISO format, yyyy-mm-dd.

/gustav
0
 

Author Comment

by:klog_69
ID: 17982265
gustav,

I am aware of what you are saying with the #'s for representing dates, but I am avoiding the string concatenations and the trouble involved with preventing SQL injection with this approach.  So I am sticking with the parameter approach.

On a note, although the actual order of the database fields may be unimportant, I will stick with what DonKyles wrote regarding parameter order:  when assigning the values to the parameters, they should be in same order as when they appeared in the SQL statement.  I have swapped the order around and sure enough I received the error again.  

I will go ahead an award DonKyles the points for the explaination.

Thanks for the help.

Phil
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to SQL Trace a SPECIFIC query 24 84
SQL replication over high latency link 10 61
Perl Versus AWK? 7 52
subtr returning incorrect value 8 33
I annotated my article on ransomware somewhat extensively, but I keep adding new references and wanted to put a link to the reference library.  Despite all the reference tools I have on hand, it was not easy to find a way to do this easily. I finall…
Using SQL Scripts we can save all the SQL queries as files that we use very frequently on our database later point of time. This is one of the feature present under SQL Workshop in Oracle Application Express.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question