?
Solved

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

Posted on 2006-11-15
8
Medium Priority
?
1,340 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
LVL 6

Accepted Solution

by:
DonKyles earned 375 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 51

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

When it comes to protecting Oracle Database servers and systems, there are a ton of myths out there. Here are the most common.
Backups and Disaster RecoveryIn this post, we’ll look at strategies for backups and disaster recovery.
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

752 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