c# Insert boolean value into database - c#

I have problem inserting boolean value into database.
I have simple structure:
struct
{
string name;
bool isStudent;
}
and I want to insert it into data base like this:
dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', " + people1.isStudent + ")";
dbCommand.ExecuteNonQuery();
but i throws exception:
SQLite error no such column: True

Try using:
dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', '" + people1.isStudent + "')";
Note that 'true' or 'false' will be quoted this way.
Or:
int val = isStudent ? 1 : 0;
dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', " + val + ")";
1 will be used for true values and 0 for false values.

Use parameters and you won't have to worry about quotes or format of the values (besides, it is a good practice to avoid SQL injection):
dbCommand.CommandText = "INSERT INTO People (name, isStudent)
VALUES (#name, #isStudent)";
dbCommand.Parameters.AddWithValue("#name", people1.name);
dbCommand.Parameters.AddWithValue("#isStudent", people1.isStudent);
dbCommand.ExecuteNonQuery();

SQLite doesn't have a bool column type and you're constructing the SQL statement yourself. If you want to do that, then convert 1 and 0 back and forth.
I would also think the .net wrapper would do that 4 u. But you would have to use SQL parameters and not build the string yourself to even give it a chance to do that.
Building parameterized queries (?) also let's SQL lite cache the compiled statements.

Related

C# MySQL Error “Column count doesn't match value count at row 1”

MySqlCommand cmd1 =
new MySqlCommand(
"INSERT INTO quotedetails (name, address, district, date, forto, refto, total) VALUES('" + txttoname.Text + "', '" + txttoaddress.Text.Replace("\r\n", "<br />").ToString() + "', '" + txtdistrict.Text + "' , '" + dateTimePicker1.Value.Date.ToString("yyyy-MM-dd") +"', '" + txtfor.Text + "', '" + txtref.Text + "', '" + txttotal.Text + "')", conn);
{
Can I get some help please? Im getting Column count doesn't match value count at row 1 when the command1 is executed.
You should never use SQLs like this. It is prone to SQL Injection attacks. When you use it like yours, one can steal confidential information from database or even delete your tables, data etc. For details please read SQL Injection on wiki
Instead you should use parameterized SQL queries. In that way you are safe from injection attacks and I believe it is much more practical to write sql.
In your case entering single ' char into one of the textboxes will cause your query to get exception. To fix the issue just use prameters.
For your case you can write something like that.
string sqlString = #"INSERT INTO quotedetails (
name,
address,
district,
date,
forto,
refto,
total)
VALUES (
#PAR_name,
#PAR_address,
#PAR_district,
#PAR_date,
#PAR_forto,
#PAR_refto,
#PAR_total)";
MySqlCommand cmd1 = new MySqlCommand(sqlString, conn);
cmd1.Parameters.AddWithValue("PAR_name", txttoname.Text);
cmd1.Parameters.AddWithValue("PAR_address", txttoaddress.Text.Replace("\r\n", "<br />"));
cmd1.Parameters.AddWithValue("PAR_district", txtdistrict.Text);
cmd1.Parameters.AddWithValue("PAR_date", dateTimePicker1.Value.Date);
cmd1.Parameters.AddWithValue("PAR_forto", txtfor.Text);
cmd1.Parameters.AddWithValue("PAR_refto", txtref.Text);
cmd1.Parameters.AddWithValue("PAR_total", txttotal.Text);
Please note that I use prefix PAR_ for my sql parameters, it is just a convention you can use that or skip PAR_ prefix does not matter and it is all about naming habits.
Additionaly; in a parameterized query, you don't need to convert all your values to string. You can use DateTime for your date field or you can pass int variable without using ToString() as you do before.
On the face of it, this happens when the number of values are more or less than columns provided.
From your statement, this does not seem to be the case. BUT since you are providing uielements directly into insert statement (Textbook case of SQL Injection), I am guessing there is a single quote ' in any of your ui elements, which breaks your insert statement.
MySqlCommand cmd1 = conn.CreateCommand();
cmd1.CommandText = "INSERT INTO quotedetails (name, address, district, date, forto, refto, total) VALUES('" + txttoname.Text + "', '" + txttoaddress.Text.Replace("\r\n", "<br />").ToString() + "', '" + txtdistrict.Text + "', '" + dateTimePicker1.Value.Date.ToString("yyyy-MM-dd") +"', '" + txtfor.Text + "', '" + txtref.Text + "', '" + txttotal.Text + "')";
Using SQL parameters will save you from lots of trouble as well as SQL injection.I am quite sure that if you use parameters your problem will be resolved:
MySqlCommand cmd1 = new MySqlCommand( "INSERT INTO quotedetails (name, address, district, date, forto, refto, total) VALUES(#name,#address,#district,#date,#forto,#refto,#total)", conn);
cmd1.Parameters.AddWithValue("#name",txttoname.Text);
cmd1.Parameters.AddWithValue("#address",+ txttoaddress.Text.Replace("\r\n", "<br />").ToString());
cmd1.Parameters.AddWithValue("#district",txtdistrict.Text);
...

Incorrect syntax in T-SQL statement in c#

I have the following code:
USE [DB] INSERT INTO Extract2_EventLog VALUES (" + li.userId + ", '" + li.startTime.ToString() + "', '" + li.endTime.ToString() + "', '" + li.elapsedTime.ToString() + (li.actionType == ActionType.REPORT ? "', 'report')" : "', 'extract')', '" + status + "'");
When I run this, I get the following error:
{"Incorrect syntax near ', '.\r\nUnclosed quotation mark after the
character string ''."}
I can't see what I'm doing wrong.. Anyone?
Man....Where to start with this...
First off, you should be using stored procedures that accept parameters (variables from your application code). Second, you should have a dataaccess layer in your application separating database calls and your user interface. I can't possible stress enough how important this is and how bad your current approach is. You will forever be fighting problems like this until you correct it.
But to address the question as it was asked...Your error is because your query string is malformatted. Use the debugging tools to view the string before it is sent to the database and then you should be able to quickly determine what is wrong with it. To troubleshoot, you can always cut and paste that string into SSMS, refine it there, and then make the necessary changes to your c# code.
First of all look at the answer of Stan Shaw, next take a look at the comment of Jon Skeet!
The first thing to do is stop building SQL like that... right now. Use parameterized SQL and you may well find the problem just goes away... and you'll be preventing SQL Injection Attacks at the same time.
They sayed everything that's important and just for the sake of giving you a direct answer:
You have a status + "'"); at your code which needs to be changed to status + "')"; ...
...like this one:
string statement = "USE [DB] INSERT INTO Extract2_EventLog VALUES (" + li.userId + ", '" + li.startTime.ToString() + "', '" + li.endTime.ToString() + "', '" + li.elapsedTime.ToString() + (li.actionType == ActionType.REPORT ? "', 'report')" : "', 'extract')', '" + status + "')";
Instead of concatenating values into your query you should use a parameterized query or a stored procedure.
A rewrite of your code could be something like (depending on datatypes, etc):
string commandText = "INSERT INTO Extract2_EventLog (userId, startTime, endTime, elapsedTime, actionType, [status]) VALUES (#userId, #startTime, #endTime, #elapsedTime, #actionType, #status)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("#userId", li.userId);
command.Parameters.AddWithValue("#startTime", li.startTime);
command.Parameters.AddWithValue("#endTime", li.endTime);
command.Parameters.AddWithValue("#elapsedTime", li.elapsedTime);
command.Parameters.AddWithValue("#actionType", li.actionType == ActionType.REPORT ? "report" : "extract");
command.Parameters.AddWithValue("#status", status);
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
You've forgot the " at the beginning. So your code reverts sql with non sql.
AND your example seems to be incomplete.

Casting datareader values to integer in insert statement

I am building an insert statement with data from an excel file using data reader values. The excel file datareader always only has one record. There are two columns in the destination table, first of type int and second column of varchar.
while (dr.Read())
{
string insertstring = #"insert into configtest values
('" + dr.GetValue(0) + "','"
+ dr.GetValue(1) + "')";
}
SqlCommand commandInsert = new SqlCommand(insertstring, conn);
commandInsert.ExecuteNonQuery();
I get error
"Error converting varchar type to numeric.
I tried casting the first value to type int and get a
"Specified cast is not valid"
error. Please help with this.
If the first column in the destination table is an integer column you should not pass a string.
In your concatenation command you put single quotes around the first parameter and this means you try to pass a string. Thus the error.
However you should always write a parameterized query, not try to build a sql command using string concatenation
string insertstring = #"insert into configtest values (#p1, #p2)";
while (dr.Read())
{
SqlCommand commandInsert = new SqlCommand(insertstring, conn);
if(dr.IsDBNull(0))
commandInsert.Parameters.AddWithValue("#p1", DBNull.Value);
else
commandInsert.Parameters.AddWithValue("#p1", Convert.ToInt32(dr[0]));
if(dr.IsDBNull(1))
commandInsert.Parameters.AddWithValue("#p2", DBNull.Value);
else
commandInsert.Parameters.AddWithValue("#p2", dr[1].ToString());
commandInsert.ExecuteNonQuery();
}
This approach will keep you safe from Sql Injection and from syntax error triggered if your string values contain single quotes.
As a final note, keep in mind that when a DataReader is open you cannot use its connection for other activities (ExecuteNonQuery) unless you use the MultipleActiveResultSets=True in your connection string
Replace your string with following (assuming your dr.GetValue(0) is int.)
string insertstring = #"insert into configtest values
(" + dr.GetValue(0) + ",'"
+ dr.GetValue(1) + "')";
Just removed quotes around dr.GetValue(0). As it is of type int it does not require quotes.
EDIT:
To insert null values, you can check for null values in query itself-
string insertstring = #"insert into configtest values
(" + (dr.GetValue(0) == null ? System.Data.SqlTypes.SqlInt32.Null : dr.GetValue(0)) + ",'"
+ (dr.GetValue(1) == null ? string.Empty : dr.GetValue(1)) + "')";
Though this is not the perfect solution but can do a workaround !!!!

Error in SQL syntax;check the manual that corredponds to your MySQL server

I am trying to insert a record to a mysql database using c# but I always saw this error message:
You have error in your SQL syntax;check the manual that corredponds to
your MySQL server version for the right syntax to use near
'Order(idOrder, Quantity, Date, Menu_idMenu)VALUES(10002,
'1', '3/17/2013 12:00' at line 1
this is the code:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow)
{
com.CommandText = "INSERT INTO Order (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";
int insert = com.ExecuteNonQuery();
}
}
what does it mean?
You have reserved keywords in your query, Order. Quote it and be happy.
com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";
Also, it is good practice to use parameters.
Date and Order are reserved keywords on MySQL.
Use them between ''
com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";
And always use parameterized queries. This kind of codes open for an SQL Injection attacks.
Actually, you can use Date without quotes.
MySQL permits some keywords to be used as unquoted identifiers because
many people previously used them.
Since, I suggest you using parameterized queries, here how you can use it with your code;
com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (#idOrder, #Quantity, #Date, #Menu_idMenu)";
com.Parameters.AddWithValue("#idOrder", "10002");
com.Parameters.AddWithValue("#Quantity", row.Cells[0].Value.ToString());
com.Parameters.AddWithValue("#Date", DateTime.Today.ToString());
com.Parameters.AddWithValue("#Menu_idMenu", row.Cells[1].Value.ToString());

SQL error in asp.net

if you please help me i am having a problem in sql code asp.net C#.
my error is:
System.Data.SqlClient.SqlException was unhandled by user code
Message=Incorrect syntax near ')'.
and my query code goes as follows:
string query = #"insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails)
values(" + 0 + "," + ListBox4.SelectedValue +"," + ListBox1.SelectedValue + "," + null + ")";
You can't insert null like that way. Use parameterized query.
string query = "insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails)
values (#overall_rating,#paper_id,#conference_role_id,#details)";
cmd=new SqlCommand(query,cn);
cmd.Parameters.AddWithValue("#overall_rating",0);
cmd.Parameters.AddWithVaule("#paper_id",ListBox2.SelectedValue);
cmd.Parameters.AddWithValue("#conference_role_id",Listbox1.SelectedValue);
cmd.Parameters.AddWithValue("#details",DBNull.Value);
Yes, as everybody else said already, you can't use null the way you are doing it but there are more serious issues than that:
Your sql statement is prone to SQL Injection attacks because you are not parametrizing your query
If you are not inserting a value into a column, simply don't list the column! This will work:
string query = #"insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID)
values(" + 0 + "," + ListBox4.SelectedValue +"," + ListBox1.SelectedValue +")";
I think the null is probably making things angry:
string query = #"insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails)
values(0," + ListBox4.SelectedValue +"," + ListBox1.SelectedValue + ",null)";
You'll notice I made your 0 part of the string and made the null part of the string (instead of concatenating integer 0 and a NULL value with the string)
What you are doing with this example is you are creating a SQL string that you plan on sending to the Database that will be executed there. When you are making your string the result of the string is something like...
"insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails) values(0, someValueFromListbox4,someOtherValueFromListbox1,)"
You will notice that the final parameter is missing. To fix this try this...
string query = #"insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails)
values(" + 0 + "," + ListBox4.SelectedValue +"," + ListBox1.SelectedValue + ",NULL)";
Here is another example using string.format which I would reccommend
string query = String.format("Insert into ReviewPaper(Overall_Rating,Paper_ID,Conference_Role_ID,Deitails) Values(0,{0},{1},NULL)", ListBox4.SelectedValue, ListBox1.SelectedValue);
Try putting the null within the speech marks so the end looks like ",null)";

Categories

Resources