Incorrect Syntax when creating table from textbox name - c#

I was trying to create a table based on the name given in textbox1 .I am getting error in the following code :
Incorrect syntax near 'Ramesh'.
Here Ramesh was the value in textbox.
string Customername = Textbox1.text
SqlCommand cmd7 = new SqlCommand("CREATE TABLE '" + CustomerName + "' (ItemCode int,Quantity int,PricePerQuantity int,Brand char(50),Discount int , DateTime datetime)",connection

You don't need single quotes for your table name.
SqlCommand cmd7 = new SqlCommand("CREATE TABLE " + CustomerName + " (ItemCode int,Quantity int,PricePerQuantity int,Brand char(50),Discount int , DateTime datetime)",connection);
But weird part, don't use SqlCommand for MySQL. Use MySqlCommand and related class.
Also I would say that use parameterize queries but since you can't parameterize column name, and looks like you get it as an input, use strong validation or use whitelisting before you put it in your query.
You can read: The BobbyTables culture

remove ' from sides of the table name in query.
string Customername = Textbox1.text
SqlCommand cmd7 = new SqlCommand("CREATE TABLE " + CustomerName + " (ItemCode int,Quantity int,PricePerQuantity int,Brand char(50),Discount int , DateTime datetime)",connection

The immediate cause of the error is that you should not put table name into apostrophes. Something like this:
// put IDisposable into using
using (SqlCommand cmd7 = new SqlCommand(
// Keep SQL readable; "$" - C# 6.0 feature
$#"CREATE TABLE {Textbox1.text}(
ItemCode int,
Quantity int,
PricePerQuantity int,
Brand char(50),
Discount int,
DateTime datetime)",
connection)) {
cmd7.ExecuteNonQuery(); // execute and create the table
}

Related

SQL Server Numeric, can create but not update using C#

Just a simple quick question, I'm using Microsoft SQL Server 2014 Express and now I have two functions to create a record and to update a record containing a numeric value.
For some unknown reason I can create the record using a numeric value with a number bigger than 0 after the decimal point (like 50.50), however, when trying to update this record with the numeric value it just says that my syntax is wrong after the decimal point. So tl,dr (50.00 works, 50.50 or something like that, doesn't).
My question now is: what am I doing wrong?
Here are my two functions:
public static void UpdateProduct(int id, string name, decimal price)
{
try
{
string query = "UPDATE dbo.Products SET Name = '" + name + "' , Price = " + price + " WHERE ProductID = " + id;
SqlCommand command = new SqlCommand(query, connection);
command.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
public static void AddProduct(string name, decimal price)
{
string query = "INSERT INTO dbo.Products (Name, Price) VALUES (#name, #price)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#name", name);
command.Parameters.AddWithValue("#price", price);
command.ExecuteNonQuery();
}
And here is my SQL create for this value
create Table Products
(
ProductID INT IDENTITY(1,1) PRIMARY key,
Name VARCHAR(255) NOT NULL,
Price NUMERIC(5,2) NOT NULL,
Active BIT DEFAULT 1
);
In your insert query you use query parameters, which, among other things, take care of correct formatting of your decimal value.
In you update query you use string concatenation to add you decimal to the query. Most certainly, your current culture formats the decimal point not as point but as comma, resulting in an syntactically incorrect query.
So your assignment of
string query = "UPDATE dbo.Products SET Name = '" + name + "' , Price = " + price + " WHERE ProductID = " + id;
Will result in a string like
UPDATE dbo.Products SET Name = 'somename' , Price = 50,5 WHERE ProductID = 3
Instead of
UPDATE dbo.Products SET Name = 'somename' , Price = 50.5 WHERE ProductID = 3
Use parametrized queries like in the insert and this problem -- and many potential others you didn't even notice yet -- will be gone.

C# Alter Table and Add a column programmatically ASP.Net & SQL Server

I have been trying to add a column programmatically in ASP.NET to modify the tables in SQL Server.
Please see the following code:
string suppliernotxt = supplieridlist[1].ToString();
//SqlCommand cmd2 = new SqlCommand("ALTER TABLE [ProductNormalDB] ADD suppliernotxt nvarchar(20) NULL", con);
SqlCommand cmd2 = new SqlCommand("ALTER TABLE ProductNormalDB ADD #supplierlist nvarchar(20) NULL", con);
cmd2.Parameters.AddWithValue("#supplierlist", suppliernotxt);
//cmd2.Parameters.AddWithValue("#supplierlist", suppliernotxt.ToString());
//cmd2.Parameters["#supplierlist"].Value = supplieridlist[x];
cmd2.ExecuteNonQuery();
supplieridlist is an array that acquires all the column names to add into the SQL Server database. For some reason the parametrized method is not working and shows the following error:
Incorrect syntax near '#supplierlist'.
The basic idea is to have a user select from a check box the name of the suppliers, based on the selected number of suppliers the array will create the supplier names for ex. if we selected 3 suppliers, the array will save "Supplier1", "Supplier2", "Supplier3" and then the SqlCommand is supposed to alter the table and add the new columns.
You cannot use parameters to express the name of columns.
Parameters could only be used to express values for WHERE clause or for INSERT or UPDATE statements.
You could use string concatenation for your query text, passing the string value to a stored procedure or use some form of dynamic sql.
Please be very carefull with these kind of approaches because if you don't keep absolute control on the values passed to your code you will be exposed to Sql Injection.
Adding as an example of Dynamic SQL execution, but still vulnerable to SQL Injection
string suppliernotxt = supplieridlist[1].ToString();
string execSQL = "DECLARE #sup nvarchar(15); " +
"SET #sup = '" + suppliernotxt + "'; " +
"EXEC ('ALTER TABLE ProductNormalDB ADD ' + #sup + ' nvarchar(20) NULL')"
SqlCommand cmd2 = new SqlCommand(execSQL, con);
cmd2.ExecuteNonQuery();
As you can see, even with Dynamic SQL there is nothing that prevent an SQL Injection attack passing via the suppliernotxt variable
EDIT As explained in the comments below from #RBarryYoung, a good improvement on the SQL Injection problem for this case of dynamic sql could be the usage of the QUOTENAME function to obtain an Unicode string with the required delimiters around the input string
string execSQL = "DECLARE #sup nvarchar(15); " +
"SET #sup = QUOTENAME('" + suppliernotxt + "'); " +
"EXEC ('ALTER TABLE ProductNormalDB ADD ' + #sup + ' nvarchar(20) NULL')"

Insert datetime from C# into SQL Server database

when I try to insert datetime value into a SQL Server database I get this error:
Conversion failed when converting date and/or time from character string
Code:
connection.Open();
SqlCommand command = new SqlCommand("insert into table values(#time)", connection);
command.Parameters.AddWithValue("#time", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
Table table has 1 datetime column called time.
Edit:
my table created in msSQL 2012: http://i.imgur.com/TJ3t3y7.png
my real code is:
public void vytvorDotaz(String uzivatel, DateTime cas, String nazev, String dotaz)
{
int id = getMaxID() + 1;
connection.Open();
SqlCommand command = new SqlCommand("insert into otazky values('" + id + "', '" + uzivatel + "', '0','0','0','#cas','" + nazev + "','" + dotaz + "')", connection);
command.Parameters.AddWithValue("#cas", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
}
The actual problem here is that you're writing the parameter inside quotes:
... ,'0','#cas',' ...
^ ^
This will not use #cas as a parameter, you're actually trying to insert the string "#cas" into that column, not the contents of the parameter #cas.
Remove the quotes and that part should work.
Additionally, don't use string concatenation to build up the SQL, use parameters for everything, save you some headache from SQL injection attacks or quotes or whatnot. This is related to the "id", "uzivatel", "nazev", and "dotav" parameters you're using (method parameters that is).
Looks like you need:
insert into table values(#time)
Without the single character quote.
Try System.Data.SqlTypes.SqlDateTime Also when storing dates please consider storing them as UTC to prevent confusion.

DateTime operator giving strange results

I have two SQL query strings, one of which works and one of which doesn't.
The working one:
string updateLoginTime = "UPDATE DeviceUsers SET lastLogin = '" + dateTime + "' WHERE ID = '" + userID + "'";
This one doesn't:
string updateText = "UPDATE DocumentsRead SET timeRead = '" + dateTime + "' WHERE userID = '" + userID + "' AND fileName = '" + fileOnly +"'";
It throws an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
In both queries the dateTime parameter is passed into a web method as a string.
Any ideas why the first one works but the second doesn't?
-EDIT-
The second query is now formatted as follows:
dateTime = DateTime.Now.ToString("dd-MM-yy HH-mm-ss");
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EndUsersConnectionString"].ConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "UPDATE DocumentsRead SET timeRead = #timeRead WHERE userID = #userID AND fileName = #fileName";
cmd.Parameters.AddWithValue("#timeRead", dateTime);
cmd.Parameters.AddWithValue("#userId", userID);
cmd.Parameters.AddWithValue("#fileName", fileName);
cmd.ExecuteNonQuery();
}
Still getting the same error.
Never do that. NEVER use string concatenations to build SQL queries. ALWAYS use parametrized queries if you don't want to meet Bobby Tables:
using (var conn = new SqlConnection(someConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "UPDATE DocumentsRead SET timeRead = #timeRead WHERE userID = #userID AND fileName = #fileName";
cmd.Parameters.AddWithValue("#timeRead", someDateTimeInstance);
cmd.Parameters.AddWithValue("#userId", userId);
cmd.Parameters.AddWithValue("#fileName", fileName);
cmd.ExecuteNonQuery();
}
This way not only that you won't meet with Bobby Tables but your query will work correctly.
The golden rule that should be respected when doing SQL development is not never use the + operator.
Double check your datatypes on the table properties.
DeviceUsers.lastLogin type seems to be correctly set to Date, but perhaps DocumentsRead.timeRead isn't correctly configured.
Concatenating sql query is a bad practice in common so it is better to use parametrized query, however in your case you're possibly working in an environment with different locales so the application server and dbms use different date formats (dd/mm/yyyy and mm/dd/yyyy for example)

C# update database

I'm using this string to update database and in this case, it works fine. It updates Znesek_nakupa in in last row:
string sqlUpd = "UPDATE Racun SET Znesek_nakupa='10' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";
But when I'm trying to insert variable and not just 10 it gives me error:
Error converting data type varchar to numeric.
Code example:
double totalPrice = 1.1;
string sqlUpd = "UPDATE Racun SET Znesek_nakupa='totalPrice' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";
How can I do this?
This problem less to do with SQL, and more to do with using strings and variables in C#.
In order to insert the value of a variable in a string in C#, you can't just place the name of the variable in the string. The string doesn't "know" that it contains a variable. Here are a couple of approaches that will work instead:
double totalPrice = 1.1;
// string concatenation
string sqlUpd =
"UPDATE Racun SET Znesek_nakupa='" +
totalPrice +
"' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";
// with string.Format
string sqlUpd = string.Format(
"UPDATE Racun SET Znesek_nakupa='{0}' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)",
totalPrice);
However, the approach of just embedding a variable's value in a SQL query like this is not considered best practice as it risks SQL injection attacks. Usually you would want to use parameterised SQL queries.
A parameterised version of your query would look like this (lifting the example from the page linked to above):
SqlConnection conn = new SqlConnection(_connectionString);
conn.Open();
string s = "UPDATE Racun SET Znesek_nakupa='#totalPrice' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun";
SqlCommand cmd = new SqlCommand(s);
cmd.Parameters.Add("#totalPrice", totalPrice);
SqlDataReader reader = cmd.ExecuteReader();
Ok, I got it.
When I try to save variable totalPrice in database it comes to error, because C# has comma as separator. In database I have to send dot instead. So I simple replace comma with dot and now it works perfect.
So code looks like this now:
string sqlUpd = "UPDATE Racun SET Znesek_nakupa='" + Convert.ToString(totalPrice).Replace(',', '.') + "' WHERE Id_racun= (SELECT MAX(Id_racun) FROM Racun)";

Categories

Resources