Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert unicode (arabic) characters into SQL Server database [duplicate]

I want to insert Unicode letters I have already tried changing the data types to nvarchar(max) and my select statement is

string str = "insert into Table1( (N'title), datee, post, cat, imageurl) values  ('" + TextBox1.Text + "','" + DateTime.Now.ToShortDateString() + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Text + "','" + path+"')";`
like image 639
coderoaq Avatar asked Jul 09 '26 17:07

coderoaq


1 Answers

You should always use parametrized queries to avoid SQL injection attacks. Parameters also give you the ability to explicitly define what data types and which length you want. Furthermore, by using parameters, you don't need to fiddle with lots of single and double quotes and so forth - the code becomes much cleaner and easier to read - and you avoid a lot of errors, too!

Try code something like this:

// define your INSERT statement with PARAMETERS
string insertStmt = "INSERT INTO dbo.Table1(title, datee, post, cat, imageurl) " +
                    "VALUES(@title, @datee, @post, @cat, @imageurl)";

// define connection and command
using(SqlConnection conn = new SqlConnection(yourConnectionStringHere))
using (SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
     // define parameters and set their values
     cmd.Parameters.Add("@title", SqlDbType.NVarChar, 100).Value = TextBox1.Text.Trim();
     cmd.Parameters.Add("@datee", SqlDbType.DateTime).Value = DateTime.Now;
     cmd.Parameters.Add("@post", SqlDbType.NVarChar, 100).Value = TextBox2.Text.Trim();
     cmd.Parameters.Add("@cat", SqlDbType.NVarChar, 100).Value = DropDownList1.SelectedItem.Text.Trim();
     cmd.Parameters.Add("@imageurl", SqlDbType.NVarChar, 250).Value = path;

     // open connection, execute query, close connection
     conn.Open();
     int rowsInserted = cmd.ExecuteNonQuery();
     conn.Close();
}
like image 126
marc_s Avatar answered Jul 11 '26 13:07

marc_s