how to Insert large string into CLOB column of Oracle in C#? - 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', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')";
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.

Related

I get an SQL syntax error when using this query

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.

Sending information to a specific column in a database C#

I Have a table with 3 columns, when an alarm goes off, I want the time of that alarm to be stored in the 2nd column of the table(AlarmActivated). Then if that alarm is turned off, it stores that time in the same row of the table but in column 3. This is my code:
String ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30";
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES" + (DateTime.Now.ToString());
SqlConnection Con = new SqlConnection(ConStr);
SqlCommand Command = new SqlCommand(Query, Con);
Con.Open();
Command.ExecuteReader();
Con.Close();
This is executed when a value goes to 0.
ExecuteReader returns some data. Since you wanna insert, you need to use ExecuteNonQuery instead.
And do not store your DateTime values as a string. Change your column type to datetime2 and pass your DateTime.Now value directly to your parameterized query. Please read Bad habits to kick : choosing the wrong data type
Also using DateTime.Now can be ambigious. Read Matt's article The case against DateTime.Now
Use using statement to dispose your connection and command automatically instead of calling Close method manually.
Since you insert only one column, other two columns will be null or their default value.
string ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30"
using(var Con = new SqlConnection(ConStr))
using(var Command = Con.CreateCommand())
{
Command.CommandText = "INSERT INTO AlarmResponse (AlarmActivated) VALUES (#alarm)";
Command.Parameters.Add("#alarm", SqlDbType.DateTime2).Value = DateTime.Now;
Con.Open();
Command.ExecuteNonQuery();
}
The problem is in
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES" + (DateTime.Now.ToString())
It has to be
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES (" + DateTime.Now.ToString() + ")";
wrong function is used, use this function: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx ExecuteNonQuery
First, your string for your insert is badly formed. You need to put the parentheses inside quotes:
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES('" + DateTime.Now.ToString() +"')";
Secondly, you need to use parameterized queries instead, because building your SQL like this is a bad habit to get into and can lead to SQL injection breaches:
String ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30";
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES (#alarmTime)";
SqlConnection Con = new SqlConnection(ConStr);
SqlCommand Command = new SqlCommand(Query, Con);
Con.Open();
Command.Parameters.AddWithValue("#alarmTime", DateTime.Now);
Command.ExecuteNonQuery();
Con.Close();
Finally, only the column AlarmActivated will be set with a value. The other two columns will be populated by their default value. If you want the other two columns to have a value other than their default, you need to specify them and provide a value.
You can create 2 stored procedures in SQL, one will insert row and return ##SCOPE_IDENTITY (you can store it in list<>), which you will use as a param for updating procedure.
Try to avoid using SQL statemensts in code, to prevent code injection.

Inserting special chars (such as ' or +) into an Access database

I have not much experience with SQL, Access nor C# but I find no solution to a problem that should look quite simple for someone who has more expertise.
Basically, the user fill some textboxes in a Winform and he might insert some "special" characters (at least, special for DB strings) such as '. These data are hence transferred into the database through an OleDb connection; let's say that string myString = this.textBox1.Text is the value that I would like to insert into the field MY_FIELD of the table myTable.
Starting code
My starting code was straight-forward:
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + this.DBstring);
OleDbCommand comm = new OleDbCommand();
comm.CommandText = "INSERT INTO myTable (MY_FIELD) VALUES ('" + myString + "')";
comm.CommandType = CommandType.Text;
comm.Connection = conn;
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
The above code will easily fail in the case where myString is something like guns'n'roses, because the comm.CommandText will be the following string value which is not valid SQL: INSERT INTO myTable(MY_FIELD) VALUES ('guns'n'roses').
Further research
I wasn't obviously the first newbie having this kind of problem. So I searched a bit through Stack Overflow and found the following thread where a guy had an issue inserting brackets into the command string. Hence, I've tried to adapt my code as for the accepted answer:
comm.CommandText = "INSERT INTO myTable (MY_FIELD) VALUES (?)";
comm.Parameters.Add(myString);
but this raises an InvalidCastException saying that The OleDbParameterCollection only accepts non-null OleDbParameter type objects, not String objects.
Could anyone please lead me to what's the best practice to insert any kind of string into the Access database without failing the SQL command due to characters that have a "special" meaning to the SQL interpreter?
You are correct in using OleDbParameter for this. Every time you want to pass values to your database engine you should use parameters. The only problem with your second attempt is the fact that you don't use the correct syntax to create and add a parameter to the command collection
comm.CommandText = "INSERT INTO myTable (MY_FIELD) VALUES (?)";
comm.Parameters.Add("#name", OleDbType.VarWChar).Value = myString;
This of course if your MY_FIELD is a text field, if it is numeric then you need to use the appropriate OleDbType enum.
Said that I would suggest to change your code to this example
string cmdText = "INSERT INTO myTable (MY_FIELD) VALUES (?)";
using(OleDbConnection conn = new OleDbConnection(....))
using(OleDbCommand comm = new OleDbCommand(cmdText, conn))
{
conn.Open();
comm.Parameters.Add("#name", OleDbType.VarWChar).Value = myString;
comm.ExecuteNonQuery();
}
The main difference is the Using Statement. With this syntax your disposable objects (connection and command) are correctly closed and disposed after you have finished to use them releasing any system resource used. And this happens also in case of Exceptions
The .Add method of an OleDbParameterCollection has several overloads, and the ones with a single argument expect that argument to be an OleDbParameter object.
If you want to pass the string value of a parameter then you'll need to use the overload that accepts the Name, Type, and Column Width of the parameter, i.e., this one, and then assign the .Value, like so:
comm.Parameters.Add("?", OleDbType.VarWChar, 255).Value = myString;
And, as #Steve said, you should always use parameters instead of "dynamic SQL" (which is what your first attempt was doing by "gluing" the value into the SQL statement itself).

How to execute a TSQL input command in C# which includes a string with "-", "\" or ";"

I have a SqlCommand that attempts to insert a row in a SQL Server database table. The column of interest is a nvarchar(100) and the data that needs to be input will include characters such as "-", ";" and "\". When I insert a string without these characters everything works fine. When I attempt to insert a string that includes these characters the code fails because these characters are literally understood by the code and thus reports a syntax error. I have resolved such an issue in TSQL alone using dynamic sql, however I cannot find any good references to perform this action in C#. I suppose I could create a stored procedure and pass the values, but is there a way in which I could efficiently perform this using C# alone? If so, How? Or is passing values to a Stored Procedure a better approach?
Here is a simplified version of the code:
String SQLServerInstanceNames = "ussqlclus-db43\ussqlclusdb43; ussqlclus-db44\ussqltrysdb44; ussqltrys-db45\ussqltrysdb45;"
//Create Connection (Get Connection string from Server Explorer)
SqlConnection myConnection = new SqlConnection("Data Source=SERVER1;Initial Catalog=Database1;Integrated Security=True");
//Open connection
try { myConnection.Open(); }
catch (Exception e) { Console.WriteLine(e.ToString()); }
SqlCommand myCommand = new SqlCommand("INSERT INTO [dbo].[Table1]" +
"([SQLServerInstanceNames])" +
"VALUES (SQLServerInstanceNames);", myConnection);
//Execute command
myCommand.ExecuteNonQuery();
//Close connection
try { myConnection.Close(); }
catch (Exception e) { Console.WriteLine(e.ToString()); }
Try with SqlParameters. It will save you from Sql Injection as well as from your current problem.
myCommand.Parameters.AddWithValue("#param1", myValueWithCharacters);
C# uses \ as a control character. You can ignore those by prepending the string with an # character:
String SQLServerInstanceNames = #"ussqlclus-db43\ussqlclusdb43; ussqlclus-db44\ussqltrysdb44; ussqltrys-db45\ussqltrysdb45;"
Just update your code like this to include parmeters in INSERT statement
SqlCommand myCommand = new SqlCommand("INSERT INTO [dbo].[Table1]" +
"([SQLServerInstanceNames])" + "VALUES (#SQLServerInstanceNames);", myConnection);
myCommand.Parameters.AddWithValue("#SQLServerInstanceNames", "instance name");
Notice I updated VALUES part and added #SQLServerInstanceNames – this is how you add parameters to your query.
Now that you use parameters you won’t have to worry about special characters. These will be handled automatically.

How to save HTML content in database

I have text area on my page. In that area I have to add some HTML code and save it to database. And it works for simple html, but when I select some text from "wikipedia" for example and paste it and try to save when SQL Query need to be executed I got exception with following error:
Incorrect syntax near 's'.
The identifier that starts with '. Interestingly, old maps show the name as <em>Krakow</em>.</p>
<p>Kragujevac experienced a lot of historical turbulence, ' is too long. Maximum length is 128.
The identifier that starts with '>Paleolithic</a> era. Kragujevac was first mentioned in the medieval period as related to the public square built in a sett' is too long. Maximum length is 128.
The label 'http' has already been declared. Label names must be unique within a query batch or stored procedure.
The label 'http' has already been declared. Label names must be unique within a query batch or stored procedure.
Unclosed quotation mark after the character string '>Belgrade Pashaluk</a>.</p>'
I am using asp mvc and razor engine. I don't know maybe I need to encome html somehow. I have also added this for ArticleText property:
[AllowHtml]
public string ArticleText { get; set; }
This is code for saving to database:
string sql = #"insert into tbl_articles
(Text) values
("'" + article.ArticleText"'"+")";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
Wow, NO, NO, NO. Your code is vulnerable to SQL injection and very bad stuff will happen if you don't use parametrized queries. So use parametrized queries.
using (var conn = new SqlConnection("some conn string"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "insert into tbl_articles (Text) values (#Text)";
cmd.Parameters.AddWithValue("#Text", article.ArticleText);
cmd.ExecuteNonQuery();
}
Everytime you use the + operator to concatenate strings when building a SQL query you are doing something extremely dangerous and wrong.
Try to save this way:
string sqlQuery = "INSERT INTO tbl_articles (Text) VALUES (#text)";
SqlCommand cmd = new SqlCommand(sqlQuery, db.Connection);
cmd.Parameters.Add("#text", article.ArticleText);
cmd.ExecuteNonQuery();
Try:
string sql = #"insert into tbl_articles
(Text) values
(#articleText)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#articleText",
Server.HtmlEncode(article.articleText));
cmd.ExecuteNonQuery();
This is a classic example of opening your system to a Sql injection attack.
You need to escape the ' character because if the Html contains the ' character, it will break the SQL Statement when it is executed.
EDIT: Use Darins solution to solve the problem.
this should be parameterized:
public void foo(string connectionString, string textToSave)
{
var cmdString = "insert into tbl_articles (text) values (#text)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand comm = new SqlCommand(cmdString, conn))
{
comm.Parameters.Add("#text", SqlDbType.VarChar, -1).Value = textToSave;
comm.ExecuteNonQuery();
}
}
}
(this is the gereral idea, it's not completely functional as written.)

Categories

Resources