MySQL / c#

Associate
Joined
6 Apr 2007
Posts
306
Location
Hull, UK
Could anyone give me some pointers on this problem. Been playing about with it for a few hours and I'm going round in circles.

Its been quite a learning curve this afternoon / evening (well to a novice) getting an Arduino to communicate over Xbee, then having this program pick up the serial data and attempt to put it into a database at timed intervals.

Code:
string SQLquery = @"INSERT into Kingswood_outside1 (date, time, temp) VALUES (CURDATE(), CURTIME(), " +strTempData+ ");";
            try
            {
                connection = new MySqlConnection();
                connection.ConnectionString = cs;
                connection.Open();
                MySqlCommand cmd = new MySqlCommand(SQLquery, connection);
                cmd.ExecuteNonQuery();
                connection.Close();

Its coming up with an exception everytime and I know its something to do with how I'm inserting the variable in the SQL query but I can't for the life of me work out how to fix it.

Once the exception has been caught, the program sits there quite happily doing what I want it to... just frustrating having the error.

Anyone any pointers?


Thanks!
 
Last edited:
Associate
Joined
7 Apr 2012
Posts
2,101
Location
Tampa Bay
I'm assuming strTempData is a string so the query needs to be in quotes (I added ' around " +strTempData+ "):
Code:
string SQLquery = @"INSERT into Kingswood_outside1 (date, time, temp) VALUES (CURDATE(), CURTIME(), '" +strTempData+ "');";

Would be a lot better to use prepared statements, but this should get the ball rolling for you :)
 
Associate
Joined
23 Oct 2005
Posts
201
Location
North London
I know its slightly off topic, but you want to get out of the habit of using + for string concatenation. Much better to use String.Format syntax or a StringBuilder. i.e.

Code:
string SQLquery = string.Format("INSERT into Kingswood_outside1 (date, time, temp) VALUES (CURDATE(), CURTIME(), '{0}'", strTempData);
 
Associate
Joined
7 Nov 2013
Posts
255
Location
Kent, England
I know its slightly off topic, but you want to get out of the habit of using + for string concatenation. Much better to use String.Format syntax or a StringBuilder.

In general I agree, however if you are purely concatenating constants you should use + so the compiler may produce a constant string (no runtime overhead).

Oh and Chris_83, don't wait for V2 to start following good practices, use prepared statements from the start so you don't suddenly have a headache when strTempData contains funny characters or a '
 
Last edited:
Back
Top Bottom