Search code examples
c#characterpersian

How to insert Persian words into a SQL Server database?


I am just wondering how to insert Persian characters into my service-based database?

When I save my data it shows something like '???'.

I have checked such questions like this. But, the solutions were not useful.

    private void button1_Click(object sender, EventArgs e)
    {            
            objConnection.Open();

            if (ctypeCheckBox.Checked == true)                
                st = 1;          
            else if (ctypeCheckBox.Checked == false)                
                st = 0;

            string query = "INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
            SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);
            SDA.SelectCommand.ExecuteNonQuery();
            MessageBox.Show("Inserted!");

            objConnection.Close();
    }

Solution

  • Two things:

    1. Never ever combine your query string with values

      "INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
      

      Should be immediately replaced with

      "INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) 
      VALUES(@cname, @cid, @ccredit, @csession, @st, @cstartDateDate, @cendDate, @cStartTime, @cEndTimeB)";
      

    and then you should use

    SDA.SelectCommand.Parameters.AddWithValue("cname",cnameTextBox.Text);
    

    for all parameters. This will save you from a lot of problems including SQL injection.

    1. In the database your columns should have nvarchar data type.

    Good luck