insert into sql db a string that contain special character ' - c#

i want to insert to a sql table a string that might contain ' character.
what is my best way to do so ?
should i insert a \ before the ' ?
here's my command in a c# code:
SqlCommand myCommand = new SqlCommand(
String.Format(
"insert into ACTIVE.dbo.Workspaces_WsToRefile values({0},'{1}',getdate())",
folderId,
NewWorkspaceName),
myConnection);
where NewWorkspaceName might contain ' character, so the insert will cause an exception at the moment.
thanks in advanced, hadas.

You should be using SqlParameter. http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx
string query = "insert into ACTIVE.dbo.Workspaces_WsToRefile values(#folderID, #newWorkSpace, #createDate)";
using(SqlCommand cmd = new SqlCommand(query, SqlConnection))
{
SqlParameter param = new SqlParameter("#folderID", folderId);
param.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(param);
.....
}

You have only one option, forget everything else. Use Parametrized queries like this
SqlCommand myCommand = new SqlCommand("insert into ACTIVE.dbo.Workspaces_WsToRefile" +
" values(#id, #space, getDate()", myConnection);
myCommand.Parameters.AddWithValue("#id", folderId);
myCommand.Parameters.AddWithValue("#space", NewWorkspaceName);
myCommand.ExecuteNonQuery();
folderID and NewWorkspaceName, are passed to the Sql Engine inside parameters.
This will take care of special characters like quotes.
But you gain another benefit using parametrized queries. You avoid Sql Injection Attacks

NewWorkspaceName= NewWorkspaceName.Replace("\'","\'\'");
'' is a ' in sql

You can try this:
string stringToDatabase=Server.HtmlEncode("կҤїАͻBsdҤїА");
This saves 'stringToDatabase' in your database
. Then while retreiving
string OriginalText=Server.HtmlDecode(stringFromDatabase);

Related

Updating Values with C# in SQL Table

I was wondering if it is possible for the update button to save the changes made in the table. I wrote this code but I have no idea how it could possibly work
This is the code i wrote for the update button:
string conString = "Data Source=MIRANDA-PC;Initial Catalog=Futebol do Rosa;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "Update Players$ set Player Name='" + dataGridView2.Text + "";
SqlCommand cmd = new SqlCommand(selectSql, con);
con.Open();
This is the table I want to update the values in:
Well, you just need to execute your query with ExecuteNonQuery.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection and SqlCommand.
And if your table or column names more than one word, you need to use them with [] as [Player Name]. And honestly, it is a little bit weird to use $ sign in a table name.
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Update Players$ set [Player Name] = #name";
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
}
You have to execute your SQL query with your db object.
dbinstance.ExecuteSqlCommand(string sqlcommand, object[] params);
This method is both for DDL and DML.
you can also use ExecuteNonQuery method.
cmd.CommandText = "Update Players$ set [Player Name] = #Playername";
cmd.Parameters.Add("#Playername", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
The best solution (if possible) to to convert your DAL (Data Access Layer) to Entity-framework based, instead of writing your own SQL queries. This is safe-by-design and never is vulnerable to SQL Injection of any kind.
Here is some mockup code:
using (AppEntities currDb = new AppEntities)
{
Players PlayerToEdit =
from player in currDb.Players
where player.PlayerID == lngPlayerID
select player.First();
PlayerToEdit.PlayerName = dataGridView2.Text;
currDb.SaveChanges();
}
You can read about it some more here:
https://msdn.microsoft.com/en-us/data/ef.aspx

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/

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.)

SQL query error - "Column cannot be null"

I have a SQL query:
String S = Editor1.Content.ToString();
Response.Write(S);
string sql = "insert into testcase.ishan(nmae,orders) VALUES ('9',#S)";
OdbcCommand cmd = new OdbcCommand(sql, myConn);
cmd.Parameters.AddWithValue("#S", S);
cmd.ExecuteNonQuery();
Error: Column 'orders' cannot be null at System.Data.Odbc.OdbcConnection.HandleError
From the manual:
When CommandType is set to Text, the .NET Framework Data Provider for ODBC does not support passing named parameters to an SQL statement or to a stored procedure called by an OdbcCommand. In either of these cases, use the question mark (?) placeholder. For example:
SELECT * FROM Customers WHERE CustomerID = ?
The order in which OdbcParameter objects are added to the OdbcParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
Use this:
string sql = "insert into testcase.ishan(nmae,orders) VALUES ('9', ?)";
OdbcCommand cmd = new OdbcCommand(sql, myConn);
cmd.Parameters.AddWithValue("you_can_write_anything_here_its_ignored_anyway", S);
cmd.ExecuteNonQuery();
it will be helpful to you
cmd.Parameters.Add("#S", OdbcType.Char, S);

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