How to save HTML content in database - c#

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

Related

How to fix my update statement in C# API?

I wrote this below code and I am not able to update fields.
There is no error message, however my data is not getting updated.
public void UpdateTeacher(int id, [FromBody]Teacher TeacherInfo)
{
MySqlConnection Conn = Teachers.AccessDatabase();
//Open the connection between the web server and database.
Conn.Open();
//Establish a new command(query) for our database.
MySqlCommand cmd = Conn.CreateCommand();
cmd.CommandText = "update teachers set teacherfname=TeacherFname, teacherlname=TeacherLname, employeenumber=EmployeeNumber,salary=Salary where teacherid=TeacherId";
cmd.Parameters.AddWithValue("#TeacherFname", TeacherInfo.TeacherFname);
cmd.Parameters.AddWithValue("#TeacherLname", TeacherInfo.TeacherLname);
cmd.Parameters.AddWithValue("#EmployeeNumber", TeacherInfo.EmployeeNumber);
cmd.Parameters.AddWithValue("#Salary", TeacherInfo.Salary);
cmd.Parameters.AddWithValue("#TeacherId", id);
cmd.Prepare();
cmd.ExecuteNonQuery();
Conn.Close();
}
I tried insert and delete, they are working, however update query is not working.
If you look at how you are adding your parameters, you stated that the parameter name starts with an '#' symbol.
cmd.Parameters.AddWithValue("#TeacherFname", TeacherInfo.TeacherFname);
...
But if you look at your SQL text, you have not used the '#' symbol, so you need to add this at the front of all your parameter names.
cmd.CommandText = "update teachers set teacherfname=#TeacherFname, teacherlname=#TeacherLname, employeenumber=#EmployeeNumber,salary=#Salary where teacherid=#TeacherId";
As also stated in the comments, using AddWithValue is generally considered bad. See this for more details:
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

sql syntax error - not able to append string to a database

I am currently working on a dummy project in which I am making a login screen. I don't have any big intentions with the project, beside learning some C# and sql.
I am currently trying append a new user to the database which contains each username and their password, but I am for some reason getting an error message.
The entry written in the textbox should be stored in the database, but for some reason is this not happening..
I am getting an error stating I have a syntax error which I am not sure i understand.
private void create_user_username_box_Leave(object sender, EventArgs e)
{
// Add user/password to database when when someone leaves the area.
using (DbConnection connection = new SqlConnection(#"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
{
connection.Open();
using (DbCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id,password) VALUES ("+create_user_username_textbox.Text+","+create_user_password_textbox.Text+");"))
{
command.Connection = connection;
command.ExecuteNonQuery(); // System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
}
}
}
Do not do the following, ever
"INSERT INTO [dbo].[information] (id,password)
VALUES (" + someStringVariable + "," + someOtherStringVariable + ")"
Just think about what you're doing here - you're putting whatever text the user entered directly into your query string. This is the easiest way to have your database dropped or all the information it contains stolen.
Instead, use prepared statements
var commandText = "INSERT INTO [dbo].[information] (id,password) VALUES (#Username, #Password)"
using (var command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#Username", SqlDbType.VarChar).Value = create_user_username_textbox.Text
command.Parameters.Add("#Password", SqlDbType.VarChar).Value = create_user_password_textbox.Text
command.ExecuteNonQuery();
}
You should also strongly consider NOT storing passwords in plain text
Updated with suggestion to replace Parameters.AddWithValue - obviously if the column type on your database is different, set it accordingly
The values are strings so the resulting SQL command text should enclose them within single quotes.
VALUES ('"+create_user_username_textbox.Text+"','"...
However, you should really parameterise the query to prevent the potential for Sql injection attacks.
Change the string to:
VALUES (#id,#pw)"))
Add parameters to the command:
command.Parameters.Add(new SqlParameter("#id", create_user_username_textbox.Text));
command.Paramaters.Add(new SqlParameter("#pw", create_user_password_textbox.Text));
try this -
private void create_user_username_box_Leave(object sender, EventArgs e)
{
// Add user/password to database when when someone leaves the area.
using (SqlConnection connection = new SqlConnection(#"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id,password) VALUES ("+create_user_username_textbox.Text+","+create_user_password_textbox.Text+");"))
{
command.Connection = connection;
command.ExecuteNonQuery(); // System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
}
}
}

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

Unable to insert data to database in asp.net C#

I'm new in C# programming, so I'll appreciate if anyone can help me. I know there are similar question but I still can't find the solution for my problem. I'm developing a mock system, where when user bought the product, the system will store all the transaction details. the problem is, I cannot insert the data into the database. Here's the code:
using (SqlConnection conn = new SqlConnection
(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
string QueryA = "#Insert into TransDetails(AccountNumber,Amount,Provider"
+ ",Mobile Number,TransNum,TransDate, Status) "
+ " Values (#AccountNumber,#Amount,#Provider,#Mobile Number,"
+ "#TransNum,#TransDate,#Status";
using (SqlCommand cmd = new SqlCommand("InsertRecord", conn))
{
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = QueryA;
cmd.Parameters.AddWithValue("#AccountNumber", acc.Text);
cmd.Parameters.AddWithValue("#Amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#Provider", lblProvider.Text);
cmd.Parameters.AddWithValue("#Mobile Number", lblNumber.Text);
cmd.Parameters.AddWithValue("#TransNum", lblTrans.Text);
cmd.Parameters.AddWithValue("#TransDate", lblDate.Text);
cmd.Parameters.AddWithValue("#Status", status.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch
{
lblMessage.Text = "Error";
}
finally
{
conn.Close();
}
}
}
and the stores procedures are as follows:
ALTER PROCEDURE InsertRecord1
#AccountNumber int,
#Amount nchar(10),
#Provider nchar(10),
#MobileNumber int,
#TransNum nchar(10),
#TransDate date,
#Status nchar(10)
AS
Insert into TransDetails(AccountNumber,Amount,Provider,MobileNumber,TransNum,TransDate,Status)
Values (#AccountNumber,#Amount,#Provider,#MobileNumber,#TransNum,#TransDate,#Status)
return
Really appreciate any help.
P/S: i dont know why the beginning of the stored procedures started with "alter".
I may be reading it wrong, but it looks like your stored procedure is not used at all. Try commenting out "cmd.CommandText = QueryA;" and substitute "cmd.CommandText = "InsertRecord1";" and change CommandType to StoredProcedure.
QueryA, by the way, is missing a paren at the end. However, the whole thing is unnecessary since you have a stored procedure that does the same thing and it's almost always preferable to use a stored procedure rather than embedded DML.
You must escape Mobile Number while brackets
Insert into TransDetails(AccountNumber,Amount,Provider,[Mobile Number],...
and remove the space in your parameter
...,#MobileNumber,#TransNum,#TransDate,#Status
and change the paramname in your command parameter
cmd.Parameters.AddWithValue("#MobileNumber", lblNumber.Text);
but seeing your stored procedure, the column Mobile Number has no space between it. Is it a typo error in your query on QueryA? If it is, then remove the space on it (also on parameter name)
Insert into TransDetails(AccountNumber,Amount,Provider,MobileNumber,...
or
change your CommandType.Text to CommandType.StoredProcedure and remove this line,
cmd.CommandText = QueryA;
You're using the wrong overload of the SqlCommand constructor. According to MSDN:
new SqlCommand(string, SqlConnection) Initializes a new instance of the SqlCommand class with the text of the query and a SqlConnection.
What you need to do is either set your CommandType for the sql command to CommandType.StoredProcedure and not use QueryA, or initialize the sql command with QueryA and not make use of your stored procedure.
As you can see there is # at the start of your SQL Statement.
Also you are not really using the Store Procedure.
You can Try this:
using (SqlConnection conn = new SqlConnection (ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("InsertRecord1", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#AccountNumber", acc.Text);
cmd.Parameters.AddWithValue("#Amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#Provider", lblProvider.Text);
cmd.Parameters.AddWithValue("#Mobile Number", lblNumber.Text);
cmd.Parameters.AddWithValue("#TransNum", lblTrans.Text);
cmd.Parameters.AddWithValue("#TransDate", lblDate.Text);
cmd.Parameters.AddWithValue("#Status", status.Text);
try
{
cmd.ExecuteNonQuery();
}
catch
{
lblMessage.Text = "Error";
}
finally
{
conn.Close();
}
}
Tho I don't use SQL Commands, Adapters...etc. to access the data from the SQL Database. I prefer Microsoft Data Access ApplicationBlocks which is easy-to-use library provided by Microsoft to access data from SQL Server.
Download
You can download it here http://download.microsoft.com/download/VisualStudioNET/daabref/RTM/NT5/EN-US/DataAccessApplicationBlock.msi
Introduction
https://web.archive.org/web/20210304123854/https://www.4guysfromrolla.com/articles/062503-1.aspx

insert into sql db a string that contain special character '

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

Categories

Resources