I get an SQL syntax error when using this query - c#

this works:
string sqlStr = string.Format("INSERT INTO tblFiles (filename,downloadname,description,category,length,parts,checksum,isEncrypted,uploaderIp) VALUES ('{0}','{1}','{2}','{3}',{4},{5},'{6}',{7},'{8}');",
newFile.Name.Replace("'", "''"), newFile.DownloadName.Replace("'", "''"), newFile.Description, newFile.Category, newFile.Length, newFile.Parts, newFile.Checksum, newFile.IsEncrypted, GetPeerIp());
this doesn't:
string sqlStr = string.Format("INSERT INTO tblFiles (filename,downloadname,description,category,length,parts,checksum,isEncrypted,password,uploaderIp) VALUES ('{0}','{1}','{2}','{3}',{4},{5},'{6}',{7},'{8}','{9}');",
newFile.Name.Replace("'", "''"), newFile.DownloadName.Replace("'", "''"), newFile.Description, newFile.Category, newFile.Length, newFile.Parts, newFile.Checksum, newFile.IsEncrypted, password, GetPeerIp());
Exception I get:
$exception {"Syntax error in INSERT INTO statement."} System.Exception {System.Data.OleDb.OleDbException}
my database looks like this.
I couldn't find any problem with it. Any ideas?
Thanks

Password is a reserved keyword in MS-Access sql. If you have a field with that name you need to encapsulate that name between square brackets (better change it now)
string sqlStr = #"INSERT INTO tblFiles
(filename,downloadname,description,category,length,parts,
checksum,isEncrypted,[password],uploaderIp) VALUES (.....)";
Said that, please, remove all that string concatenations and use a parameterized query. Not only this is more safe (prevents Sql Injections) but also removes all the problems with quoting and correct parsing of dates and decimal numbers
string sqlStr = #"INSERT INTO tblFiles
(filename,downloadname,description,category,length,parts,
checksum,isEncrypted,[password],uploaderIp) VALUES
(#file, #down, #desc, #cat, #len, #parts, #check, #enc, #pass, #up)";
OleDbCommand cmd = new OleDbCommand(sqlStr, connection);
cmd.Parameters.Add("#file", OleDbType.VarWChar).Value = newFile.Name;
cmd.Parameters.Add("#down", OleDbType.VarWChar).Value = newFile.DownloadName;
... and so on for all other parameters respecting the OleDbType of the column....
cmd.ExecuteNonQuery();
Notice how your query is more clear and understandable and how you don't need to call a lot of Replace just to get rid of possible embedded single quotes.

Related

how to Insert large string into CLOB column of Oracle in C#?

Does anyone know how to insert large string value into Oracle CLOB column?
I only can insert short string into CLOB column....
Can you help me find out what change I have to make from this code?
using Oracle.DataAccess.Client; //from Oracle.DataAccess.dll
using System.Data;
string _strConn =
"Data Source=(DESCRIPTION="
+ "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=LOCALHOST)(PORT=1521)))"
+ "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ORCL)));"
+ "User Id=userID;Password=userID;";
// Connect To Oracle
OracleConnection conn = new OracleConnection(_strConn);
conn.Open();
// Create Instance to command
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
// Define SQL command
cmd.CommandText = "insert into practice_clob values ('a', 'aaa')"; //This works
//This does not work with the error message, "string literal too long"
//cmd.CommandText = "insert into practice_clob values ('a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')";
cmd.ExecuteNonQuery();
conn.Close();
This is my table from Oracle...
create table practice_clob(
str varchar2(100),
clob_value clob
);
Can anyone edit the code to insert large string value into CLOB column of Oracle?
Pretty much do what Oracle tells you:
"ORA-01704: string literal too long
Cause: The string literal is longer than 4000 characters.
Action: Use a string literal of at most 4000 characters. Longer values may only be entered using bind variables."
So, just use a parameter instead. As a bonus, you'll also avoid SQL injection.

C# String literal with concatenation

I have a ASP.NET C# application, and I frequently use the verbatim string literal such as
dbCommand.CommandText = #"INSERT INTO MYTABLE (COLUMN, COLUMN2)
VALUES ('data', 'data)";
This is all great, but when I try to concatenate the string with a variable such as
dbCommand.CommandText = #"INSERT INTO MYTABLE" + Session["table_extension"] + "(COLUMN, COLUMN2)
VALUES('data','data')";
I get an error stating Newline in constant. How can I avoid this while still using the # string literal?
Put the # in front of the second string literal or use String.Format()
1) Don't concatenate strings to build SQL commands, it's really dangerous and error phrone (see SQL Injection: http://www.w3schools.com/sql/sql_injection.asp).
You should use ADO.NET parameters (http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06)
2) If you are going to concatenate strings, use string.Format like:
var sql = string.Format("INSERT INTO MyTable ('col1') VALUES ({0})", col1Value);
Or use the new simplified syntax which has a better compile time check:
var sql = $"INSERT INTO MyTable (col1) VALUES ('{col1Value}')";
This will work for you!
dbCommand.CommandText = #"INSERT INTO MYTABLE" + Session["table_extension"].ToString() + "(COLUMN, COLUMN2)
VALUES('data','data')";

SQL server - inserting a string with a single quotation mark

I iterate over an external source and get a list of strings. I then insert them into the DB using:
SqlCommand command = new SqlCommand(commandString, connection);
command.ExecuteNonQuery();
Where commandString is an insert into command. i.e.
insert into MyTable values (1, "Frog")
Sometimes the string contains ' or " or \ and the insert fails.
Is there an elegant way to solve this (i.e. #"" or similar)?
Parameters.
insert into MyTable values (#id, #name)
And
int id = 1;
string name = "Fred";
SqlCommand command = new SqlCommand(commandString, connection);
command.Parameters.AddWithValue("id", id);
command.Parameters.AddWithValue("name", name);
command.ExecuteNonQuery();
Now name can have any number of quotes and it'll work fine. More importantly it is now safe from sql injection.
Tools like "dapper" (freely available on NuGet) make this easier:
int id = 1;
string name = "Fred";
connection.Execute("insert into MyTable values (#id, #name)",
new { id, name });
You should look into using parameterized queries. This will allow you insert the data no matter the content and also help you avoid possible future SQL injection.
http://csharp-station.com/Tutorial/AdoDotNet/Lesson06
http://www.c-sharpcorner.com/uploadfile/puranindia/parameterized-query-and-sql-injection-attacks/

SQL INSERT - Invalid column name

As some of you may of seen from my previous post I'm new to using C# to create websites (Although I have a fair bit of experience using it for Windows Forms apps). The powers that be are tempting me away from PHP but I keep failing at what I consider the basics.
Anyway, this is my issue. I am trying to create a simple entry into a SQL database. I know my connection to the DB is fine as I can reel off SELECT queries all day long but I'm having trouble with using Insert.
Heres my code:
string filename = "abc123.jpg";
SqlConnection link = new SqlConnection(//you dont need to see my data here ;));
string sqlcode = "INSERT INTO file_uploads (upload_filename VALUES ("+filename+")";
SqlCommand sql = new SqlCommand(sqlcode,link);
link.open();
sql.ExecuteNonQuery();
This results in "Invalid column name abc123.jpg" returned from the try/catch.
Any help would be appreciated. (I wish they would let me do this in PHP lol!)
Thanks,
Tripbrock
You are missing a parenthesis after the column name and the value represents a string and as such must be enclosed in quotes:
string sqlcode = "INSERT INTO file_uploads (upload_filename) " +
"VALUES ('"+filename+"')";
However, the correct way would be to use a parameterized query:
string filename = "abc123.jpg";
SqlConnection link = new SqlConnection(/*you dont need to see my data here ;)*/);
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES (#filename)";
SqlCommand sql = new SqlCommand(sqlcode,link);
sql.Parameters.AddWithValue("#filename", filename);
link.open();
sql.ExecuteNonQuery();
your SQL is bad formatted. Try this :
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
Where upload_filename is a name of the column
Really you should be parameterising your queries - this reduces the risk of injection attacks:
string filename = "abc123.jpg";
using( SqlConnection link = new SqlConnection(/*...*/;)) )
{
// sql statement with parameter
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES (#filename)";
using( SqlCommand sql = new SqlCommand(sqlcode,link) )
{
// add filename parameter
sql.Parameters.AddWithValue("filename", filename);
link.open();
sql.ExecuteNonQuery();
}
}
Also note the using statements - these make sure that the connection and command objects are disposed of.
Try
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
You were missing a closing parentheses.
Don't know if it is a typo but the line should be:
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
Notice the ) after upload_filename.
Also also added the single quotes around the filename.
But you probably want to use a parameterized query:
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES (#filename)";
Then use command.Parameters to add the actual value.
looks like you are missing a bracket:
string sqlcode = "INSERT INTO file_uploads (upload_filename VALUES ("+filename+")";
Should be
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
Also, to avoid SQL injection attacks you can use the SQLCommand objects like so.
using (SQLCommand oSQLCommand = new SQLCommand("INSERT INTO file_uploads (upload_filename) VALUES ( #FileName )")
{
oSQLCommand.Parameters.AddWithValue("#FileName", filename);
oSQLCommand.ExecuteNonQuery();
}

once again giving the syntax error for insert into query

string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\login.mdb";
string uname, pass;
uname = textBox1.Text;
pass = textBox2.Text;
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
string query = "insert into LOGIN_TABLE (UserName, Password) VALUES ('" + textBox1.Text.ToString() + "','" + textBox2.Text.ToString() + "') ";
OleDbCommand myCommand = new OleDbCommand(query, myConnection);
//myCommand.CommandText = query;
OleDbParameter myParm = myCommand.Parameters.Add("#uname", OleDbType.VarChar, 50);
myParm.Value = textBox1.Text;
myParm = myCommand.Parameters.Add("#pass", OleDbType.VarChar, 50);
myParm.Value = textBox2.Text;
myCommand.ExecuteNonQuery();
myConnection.Close();
From the docs for OleDbCommand.Parameters:
The OLE DB .NET Provider does not
support named parameters for passing
parameters to an SQL statement or a
stored procedure called by an
OleDbCommand when CommandType is set
to Text. In this case, the question
mark (?) placeholder must be used.
There's an example on the same page.
However, you're not even using parameters in your SQL query. You're inviting a SQL injection attack by embedding the user input directly into the SQL and then also adding parameters.
Your query should just be:
String query = "insert into LOGIN_TABLE (UserName, Password) VALUES (?, ?)";
It looks like you can still give parameters names, even if they're not used - so just the change above may be enough.
EDIT: Is it possible that UserName or Password are reserved names? Try escaping them - I know in SQL Server it would be [UserName], [Password] but I don't know if that's true in Access. What happens if you try to execute the same SQL in Access, by the way?
The data you are passing as parameters might have single-quotes, ', in it.
Try this textBox2.Text.Replace("'","''") when assigning values to the parameters.
One more thing, it is not necessary to use parameters when handling simple texts and numbers in simple queries.
Your query should be like this.
string query = "insert into LOGIN_TABLE (UserName, Password) VALUES ( #uname, #pass )";
Now after that write your code, and everything will be work for you.
Whenever you are reading value from textbox, use Trim() as textBox.Text.Trim().
Sorry it will be working for SqlConnection.
Thanks

Categories

Resources