I have a button within my web page to inserts a few values into sql server columns. One of these values happens to be of data type Date. The following is my code for my asp.net page:
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into dbo.FillTable values ('TextBox2.Text', 'TextBox1.Text', 'FA0005')",con);
SqlDataAdapter dr = new SqlDataAdapter(cmd1);
con.Close();
DataSet dl = new DataSet();
dr.Fill(dl);
//Label5.Text = dl.Tables[0].Rows[1][9].ToString();
}
I want to be able to have the user enter the date in the format (yyyy-MM-dd), which is the date format for my sql server. "TextBox2" is the textbox that holds the date input. Whenever I simply hard code the date as for ex. '2010-01-01', '50', 'FA0005', it works well and inserts the record. However, when I code is as 'TextBox2.Text', 'TextBox1',etc. It gives me an error saying "Conversion failed when converting date and/or time from character string". Can someone help me with this? Its confusing me because having the date in 'yyyy-mm-dd' format works well, which is same as the textbox.
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand(string.Format("insert into dbo.FillTable values ('{0}', '{1}', 'FA0005')", TextBox2.Text, TextBox1.Text), con);
SqlDataAdapter dr = new SqlDataAdapter(cmd1);
con.Close();
DataSet dl = new DataSet();
dr.Fill(dl);
}
Now, let's break down the string.Format function. It says that if I have a string to format like this "Hello {0}!", anything I pass in at the zero index of the function will replace every occurrance of {0}. So, let's say I have this string "Hello {0}, and I say again hello {0}!" and I used it like this string.Format("Hello {0}, and I say again hello {0}!", "world"), I would get a string like this "Hello **world**, and I say again hello **world**!".
Note
However, the above solution leaves you open to SQL Injection, so if you want to protect against that then let's go this route.
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into dbo.FillTable values (#TextBox2Val, #TextBox1Val, 'FA0005')", con);
cmd1.AddParameterWithValue( "TextBox1Val", TextBox1.Text );
cmd1.AddParameterWithValue( "TextBox2Val", TextBox2.Text );
SqlDataAdapter dr = new SqlDataAdapter(cmd1);
con.Close();
DataSet dl = new DataSet();
dr.Fill(dl);
}
Now let's break this down. The statement sent to the SQL server is just what you see, with the #paramname in the string. But, it will send it as a prepare and prepare that statement with the values you provided in the AddParameterWithValue method. Note that here, as long as the value in the TextBox2.Text is a date you don't have to concern yourself with the format because SQL server will take care of that. Bear in mind that SQL server stores it in one format and you'll display it in another but it can convert from a myriad of formats as long as they are valid.
Now, as stated by #Willem, it would behoove you to ensure that the value in TextBox2.Text is in fact a date, so let's do that, add this snippet at the top of the function ...
DateTime theDate;
if (!DateTime.TryParse(TextBox2.Text, out theDate))
{
// throw some kind of error here or handle it with a default value
...
}
... and then modify the line with the AddParameterWithValue like this ...
cmd1.AddParameterWithValue( "TextBox2Val", theDate );
You don't quite have the mechanism of getting the text box values into the insert correct. Additionally this style of database insertion leaves you vulnerable to SQL Injection attacks. One better option would be to parameterize your SqlCommand, as follows:
SqlCommand cmd1 = new SqlCommand("insert into dbo.FillTable values (#Date1, #Date2, #SomeString)",con);
Then, you can specify parameters as follows:
cmd1.Parameters.AddWithValue("#Date1",TextBox1.Text);
cmd1.Parameters.AddWithValue("#Date2",TextBox2.Text);
cmd1.Parameters.AddWithValue("#SomeString,"FA0005");
Specifying parameters eliminates the SQL Injection risk, and also provides a clean mechanism for getting the values from your text boxes to your INSERT. Hope this helps.
You're inputting the text "TextBox2.Text" into the database, not the value of the textbox. Remove the quotes from TextBox2.Text:
SqlCommand cmd1 = new SqlCommand("insert into dbo.FillTable values
('" + TextBox2.Text + "', '" + TextBox1.Text + "', 'FA0005')",con);
As noted above, you're leaving yourself open to SQL Injection when you're appending strings like this.
Related
private void btn_view_Click(object sender, EventArgs e)
{
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * from tbl_emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
dgv_emptable.DataSource = ds.Tables[0];
con.Close();
}
private void btn_insert_Click(object sender, EventArgs e)
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Insert into tbl_emp(emp_id,emp_name,emp_surname,designation_id,dept_id) Values(" + txt_id.Text + " , '" + txt_name.Text + "','" + txt_phone.Text + "'," + cmb_desigid.SelectedValue + ",'" + cmb_deptid.SelectedValue.ToString() +"')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
MessageBox.Show("Record inserted");
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * from tbl_designation", con);
DataSet ds = new DataSet();
da.Fill(ds);
cmb_desigid.DataSource = ds.Tables[0];
cmb_desigid.DisplayMember = "designation_type";
cmb_desigid.ValueMember = "designation_id";
con.Close();
con.Open();
OleDbDataAdapter db = new OleDbDataAdapter("Select * from tbl_dept",con);
DataSet dm = new DataSet();
db.Fill(dm);
cmb_deptid.DataSource = dm.Tables[0];
cmb_deptid.DisplayMember = "dept_name";
cmb_deptid.ValueMember = "dept_id";
con.Close();
}
I have bound my database and I am writing an insert query to insert data in table but I get the same error at cmd.ExecuteNonQuery
no given parameters are given for required parameters.
I have checked thoroughly but can't seem to find the error
I have used textbox for emp_id,emmp_name,emp_surname,and two combo boxes for designation_id and dept_id.
the dept_id and designation_id are foreign key in tbl_emp. and i also have used the combo box property.So can anyone please tell what the error is and also if i have writtern the combo box code properly...
You need to get in the habit of using "parameterized queries" - those won't just protect your code from the #1 vulnerability out there - SQL injection - they'll also solve a lot of thorny issues with adding quotes etc. to string values.
Try this code:
private void btn_insert_Click(object sender, EventArgs e)
{
// define the insert query - OleDB uses unnamed, positional parameters
string insertQuery = "INSERT INTO tbl_emp (emp_id, emp_name, emp_surname, designation_id, dept_id) " +
"VALUES (?, ?, ?, ?, ?)";
// create command
OleDbCommand cmd = new OleDbCommand(insertQuery, con);
// define parameters - in the proper order! - and set their values
// The "names" like "#emp_id" that I'm using here are just to make it easier for you to grasp which parameter
// corresponds to which columns being inserted - you could also name them "p1", "p2" etc. - not very intuitive, though ...
// Check the *assumptions* I made for the datatypes - not sure if those are
// really what you have - adapt as needed
cmd.Parameters.Add("#emp_id", OleDbType.Int).Value = Convert.ToInt32(txt_id.Text);
cmd.Parameters.Add("#emp_name", OleDbType.VarChar, 100).Value = txt_name.Text;
cmd.Parameters.Add("#emp_surname", OleDbType.VarChar, 100).Value = txt_phone.Text
cmd.Parameters.Add("#designation_id", OleDbType.Int).Value = cmb_desigid.SelectedValue;
cmd.Parameters.Add("#dept_id", OleDbType.Int).Value = cmb_deptid.SelectedValue;
// open connection, execute query, close connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record inserted");
}
As a general side note: if you're only ever interested in a single DataTable being returned from a query - I'd strongly recommend using this code (instead of what you have now):
private void Form1_Load(object sender, EventArgs e)
{
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * from tbl_designation", con);
// define and use a "DataTable" - not a "DataSet" (which is overkill for just a single table of data)
DataTable dt = new DataTable();
da.Fill(dt);
cmb_desigid.DataSource = dt;
cmb_desigid.DisplayMember = "designation_type";
cmb_desigid.ValueMember = "designation_id";
con.Close();
I mentioned in the comments that you can get VS to do all this for you, in less time, and more securely/reliably than a human could do in a day. Writing db access code is boring and annoying, here's how you hand it off:
add a new dataset to the project, just like you would add a form or class or any other thing. Call it something sensible, not dataset1
open the server explorer window, and add a connection to your access db
drag the db into the dataset. Thoroughly read the long message box that pops up. No one reads this, and they should read it. It solves a lot of confusion later on when the build process is overwriting the database the exe is saving in, and it looks like your app never saves any data. Click yes
drag some tables out of the server explorer and into the dataset. Not the appearance of a datatabke with all the same columns as your db table and a tableadapter. This thing is NOT your database table, it is a strongly typed client side datatable which is a better version of what you're doing in your code above with weakly typed datasets and datatables. A tableadapter is a better version of a dataadapter designed to work with the better datatable it is visually attached to
switch to the forms designed
open the data sources window from the view menu, other windows submenu
drag one of the nodes out of data sources and onto the form
Many things appear, a data grid view, binding source, navigator, dataset, tableadapter, manager. Don't delete stuff until you understand how it all works because it will teach you a lot. Run the program
This app will work, load data, save data and you didn't so far write any code at all. VS wrote all the code for you and you can read it if you want, it's there in the .Designer.cs files on disk
Run the app, add some rows, change stuff, click save, close the app. Don't run the app again yet, but instead go into the bin/debug folder and open that db on there, in access. See your data you added/changed
Now close access and build the project again, now open the same bin/debug db in access.. see the data has gone? The build process copied the blank db from the project over the top of the db the exe altered when it ran. Make sure you grok what is happening here every time you build or you'll be very confused as to why your app "isn't saving" (it is, but the changes are being wiped by the build process)
Some other things you need to know about tableadapters:
they can have more than one select command- just right click them in the dataset designer and add another query. Use parameters, like SELECT * FROM t WHERE id = #id and give the command a sensible name like FillById. The tableadapter will gain a method myTabkeAdapter.FillById(someDatatableHere, 1234) to fill that datatable with row ID 1234
they have an Update method that takes a datatable. This is NOT JUST for running update queries. Update scans the whole passed on datatable looking for rows that need to be inserted updated or deleted and executes the relevant sql. When you change a datatable row, the change is tracked by the RowState property. If the rowstate is Added, and insert will be run by the table adapter, to insert the row. If the rowstate is Modified, an Update will be run. If the rowstate is deleted, a delete will be run. Microsoft should have called Update something else, like Save, because it causes confusion often
I am new to C#. I am trying to save the numbers into a SQL Server database table (locally) but I get an error:
Cannot insert the value NULL into column
My code:
private void SaveBtn_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\fn1965\Desktop\Work\TESTDB\NumDB.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
string insert_query = "INSERT into [NumericTable] (Num1, Num2, Total) VALUES (#Num1, #Num2, #Total)";
SqlCommand cmd = new SqlCommand(insert_query, conn);
cmd.Parameters.AddWithValue("#Num1", textBox1.Text);
cmd.Parameters.AddWithValue("#Num2", textBox2.Text);
cmd.Parameters.AddWithValue("#Total", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record saved");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("EROR:"+ ex.ToString());
}
}
Table schema
You can see in the image that the column Id is the only one that does not support null values. Since the column is not identity and as you are not providing a value on your insert, then the INSERT fail with the given exception. This code will work (only if there isn't a record with Id = 1 already):
string insert_query = "INSERT into [NumericTable] (Num1,Num2,Total, Id) Values (#Num1,#Num2,#Total, #id)";
SqlCommand cmd = new SqlCommand(insert_query, conn);
cmd.Parameters.AddWithValue("#Num1", textBox1.Text);
cmd.Parameters.AddWithValue("#Num2", textBox2.Text);
cmd.Parameters.AddWithValue("#Total", textBox3.Text);
cmd.Parameters.AddWithValue("#Id", 1);
cmd.ExecuteNonQuery();
I assume that this is obviously not the desired fuctionality. What you should do is either set the Id column to identity = true or set a value on the insert.
I also encourage you to not use AddWithValue method since it can lead you to some undesired problems. You can read more here: https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
That screenshot you took of your table columns design; get back to that, then click the id column, look in the Properties grid for Identity Specification (might need to expand it) and set it to Yes. Set other properties relevant to your needs and save the table.
Borrowed from another SO question:
There are ways to do this from script but they're generally longer/more awkward than using the UI in management studio.
This will (should) change th column so it auto inserts an incrementing number into itself when you insert values for other rows. Someone else has posted an answer as to how to insert values for it yourself but my recommendation to you as a learner is to use auto increment to save the additional needless complication of providing your own primary key values
I am currently working on a dummy project in which I am making a login screen. I don't have any big intentions with the project, beside learning some C# and sql.
I am currently trying append a new user to the database which contains each username and their password, but I am for some reason getting an error message.
The entry written in the textbox should be stored in the database, but for some reason is this not happening..
I am getting an error stating I have a syntax error which I am not sure i understand.
private void create_user_username_box_Leave(object sender, EventArgs e)
{
// Add user/password to database when when someone leaves the area.
using (DbConnection connection = new SqlConnection(#"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
{
connection.Open();
using (DbCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id,password) VALUES ("+create_user_username_textbox.Text+","+create_user_password_textbox.Text+");"))
{
command.Connection = connection;
command.ExecuteNonQuery(); // System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
}
}
}
Do not do the following, ever
"INSERT INTO [dbo].[information] (id,password)
VALUES (" + someStringVariable + "," + someOtherStringVariable + ")"
Just think about what you're doing here - you're putting whatever text the user entered directly into your query string. This is the easiest way to have your database dropped or all the information it contains stolen.
Instead, use prepared statements
var commandText = "INSERT INTO [dbo].[information] (id,password) VALUES (#Username, #Password)"
using (var command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#Username", SqlDbType.VarChar).Value = create_user_username_textbox.Text
command.Parameters.Add("#Password", SqlDbType.VarChar).Value = create_user_password_textbox.Text
command.ExecuteNonQuery();
}
You should also strongly consider NOT storing passwords in plain text
Updated with suggestion to replace Parameters.AddWithValue - obviously if the column type on your database is different, set it accordingly
The values are strings so the resulting SQL command text should enclose them within single quotes.
VALUES ('"+create_user_username_textbox.Text+"','"...
However, you should really parameterise the query to prevent the potential for Sql injection attacks.
Change the string to:
VALUES (#id,#pw)"))
Add parameters to the command:
command.Parameters.Add(new SqlParameter("#id", create_user_username_textbox.Text));
command.Paramaters.Add(new SqlParameter("#pw", create_user_password_textbox.Text));
try this -
private void create_user_username_box_Leave(object sender, EventArgs e)
{
// Add user/password to database when when someone leaves the area.
using (SqlConnection connection = new SqlConnection(#"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id,password) VALUES ("+create_user_username_textbox.Text+","+create_user_password_textbox.Text+");"))
{
command.Connection = connection;
command.ExecuteNonQuery(); // System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
}
}
}
I got a gridview which is connected to a datasource getting values from there.I created a selectedindexchanged function to work when select is clicked.it shows ID , orderID,From,To and Price values and opens panel which has 4 textbox's and a dropdownlist if user wants to change those values.Everything is fine until here.When user changes some values and clicks submit nothing changes in database.I got the values using id ; " string id = orderGrid.SelectedRow.Cells[1].Text; "
here is my submit button code ;
protected void submitButton_Click(object sender, EventArgs e)
{
string id = orderGrid.SelectedRow.Cells[1].Text;
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("db.mdb") + ";Persist Security Info=False");
string query = "update ordersTable set orderID=#testID,fromLocation=#from,toLocation=#to,price=#price WHERE ID = #id ";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#testID", orderBox.Text);
cmd.Parameters.AddWithValue("#from", fromText.Text);
cmd.Parameters.AddWithValue("#to", toList.SelectedItem.Text);
cmd.Parameters.AddWithValue("#price", priceBox.Text);
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Edit Complete !");
}
catch (Exception ex)
{
Response.Write("Error : " + ex);
}
orderGrid.DataBind();
}
id string works perfectly fine in my selectedindexchanged function.
In OleDb parameters are recognized by their position not by their name.
Your parameter placeholder #ID is the last one in the query, but you add it as the first one in the collection.
This result in your WHERE condition to be totally wrong
(you search for a record whose ID is equal to the content of the priceBox)
Just move the insert of the ID as last parameter
cmd.Parameters.AddWithValue("#testID", orderBox.Text);
cmd.Parameters.AddWithValue("#from", fromText.Text);
cmd.Parameters.AddWithValue("#to", toList.SelectedItem.Text);
cmd.Parameters.AddWithValue("#price", priceBox.Text);
cmd.Parameters.AddWithValue("#id", id);
This is the primary problem, but I can see another one caused by your use of AddWithValue. This is an handy shortcut, but sometime it make you pay for it.
In your case, you pass to the #price parameter a string and, if your price field is a decimal (as it should be) then the database engine will attempt a conversion from a string to a decimal and if the decimal separator is not the same you end with a wrong value in the database. Better check the value in the priceBox and convert it yourself to a decimal.
See Can we stop to use AddWithValue already?
The program is with C# WinForms and SQL Server 2008. When I want to enter data that includes the value from a DateTimePicker I can see that the wording is in Dutch and then I get an error about converting of the value. Is there any way to pre-program it to get around this? I've caught the error and here it is.
try
{
SqlConnection connect = new SqlConnection("Data Source=Localhost\\SQLExpress;Initial Catalog=DataBase;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter();
/******************** Inserting ********************/
string query = "INSERT INTO spending VALUES (";
query += "'" + date_dateTimePicker.Value + "', "; // Date
query += "'" + Convert.ToDecimal(amount_spent_textBox.Text) + "', "; // Amount spent
query += "'" + spent_on_textBox.Text + "')"; // Spent on
connect.Open();
da.InsertCommand = new SqlCommand(query, connect);
da.InsertCommand.ExecuteNonQuery();
connect.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
Things are getting thick.. I got this error while trying to insert a dateTimePicker value into the database the same way I did with the code above. It worked perfectly fine on my computer but it won't work here. Can someone explain? Here is the error:
Code used:
string update = "UPDATE table SET the_date = '" + the_date_dateTimePicker.Value + "' WHERE instance_ID = 1";
connect.Open();
da.InsertCommand = new SqlCommand(update, connect);
da.InsertCommand.ExecuteNonQuery();
connect.Close();
Ok here is the full code for the form I am working on now, the one that shows this error. Most of the forms are structured like this so if I get this one right, there shouldn't be any problems with the rest of them. I'm testing this on my computer so if it works here it should work there also.
Take a look, I don't know what to do anymore.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace TheNamespace
{
public partial class submit_spending : Form
{
public submit_spending()
{
InitializeComponent();
}
private void submit_button_Click(object sender, EventArgs e)
{
try
{
SqlConnection connect = new SqlConnection("Data Source=Localhost\\SQLExpress;Initial Catalog=TheDataBase;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter();
/******************** Inserting ********************/
string query = "INSERT INTO spending VALUES (#date, #amount_spent, #spent_on)";
SqlCommand command = new SqlCommand(query);
command.Parameters.AddWithValue("date", date_dateTimePicker.Value);
command.Parameters.AddWithValue("amount_spent", Convert.ToDecimal(amount_spent_textBox.Text));
command.Parameters.AddWithValue("spent_on", spent_on_textBox.Text);
connect.Open();
da.InsertCommand = new SqlCommand(query, connect);
da.InsertCommand.ExecuteNonQuery();
connect.Close();
if (MessageBox.Show("Submitted.", "Spending submitted", MessageBoxButtons.OK) == DialogResult.OK)
{
this.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
private void cancel_button_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
You should use the Parameters.AddWithValue() method. I would expect it to format the DateTime correctly.
string cmdText = "UPDATE table SET colX = #value WHERE id = #currId";
var cmd = new SqlCommand(cmdText, conn);
cmd.Parameters.AddWithValue("value", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("currId", id);
Probably you have problem with date time formating, It can be solved by changing the systems datetime format into the same one as in the computer it was working, or you can do some additional work in your code. For custom datetime formats Have a look here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
You can probably use an explicit ToString with a culture-invariant format to make sure that this works in any locale. This is a bit of a hack, but replacing this line:
command.Parameters.AddWithValue("date", date_dateTimePicker.Value);
with this should work:
command.Parameters.AddWithValue("date", date_dateTimePicker.Value.ToString("s"));
This will give you an ISO 8601 formatted date-time string, which is an international standard with an unambiguous specification. Also, this format is not affected by the SET DATEFORMAT or SET LANGUAGE setting on your SQL Server instance.
Ideally you should write your application using datetime parameters in the T-SQL statements so that conversions never come into picture.
The other avenue at your disposal is to add a SET DATEFORMAT on the connection(s) used by your app. You can thus change the format to the one your application expects/uses.
I think you need specify the SqlDBType when assigning the values to date in command.Parameters .and please cross check the parameter names which you have specified in insert statement with the parameters specified in parameters.Add
string sql = "INSERT INTO spending VALUES (#date, #amount_spent, #spent_on)";
using (var cn = new SqlConnection("..connection string.."))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#date", SqlDbType.DateTime).Value = date_dateTimePicker.Value;
command.Parameters.AddWithValue("#amount_spent",Convert.ToDecimal(amount_spent_textBox.Text));
command.Parameters.AddWithValue("#spent_on", spent_on_textBox.Text);
connect.Open();
Some time its better to use invariant culture to store things like date/time in database .You can try that CultureInfo.Invariantculture
DateTime date = date_dateTimePicker.Value.Date;
string sDate = date.ToString("dd-MM-yy", System.Globalization.CultureInfo.InvariantCulture);
DateTime dateInsert = Convert.ToDateTime(sDate);
Simply use dateTime.ToString("s"), it will give your date time in universal format regardless of cultural settings of the computer.
"UPDATE table SET the_date = '" + the_date_dateTimePicker.Value + "' WHERE instance_ID = 1";
A conversion to String using default CultureInfo happens here. DateTime can be converted to both "29/05/2012" and "05/29/2012" depending on the regional settings selected on your workstation. However Sql Server might be configured for another regional settings and thus you have a problem(sql server cannot parse passed string representation of DateTime)
You have to use parametrized query if you don't want to face another CultureInfo-related issue later.