我正在尝试存储从Web服务获得的一些阿拉伯值,但是当我从数据库中选择它们并在DataGridView中显示它们时,它只会显示“ ?????”.数据库中的三列是nvarchar(50).我应该如何存储它们?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string user = "gamal";
string p1 = "GAM123";
string p2 = "GAM123";
string sdate = "05152014000000";
string edate = "05182014235959";
string node = "232641";
string group = "Al Ahsa - ???????";
string Compress = "";
string m_d = "sa";
string lang = "1";
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
test_ws.ppppWebServiceSoapClient ws =
new test_ws.ppppWebServiceSoapClient("pppp Report Web ServiceSoap");
ds = ws.GetGroups(user, p1, p2);
DataSet ds_ra = new DataSet();
ds_ra = ws.RegionAlarm(user, p1, p2, sdate, edate, node, group, Compress, m_d, lang);
ds_ra.WriteXml("region_alarm.xml");
string connetionString = null;
SqlConnection connection;
SqlCommand command ;
SqlDataAdapter adpter = new SqlDataAdapter();
string sql = null;
string ID = null;
string nodegroup = null;
string nodecount = null;
connetionString = @"Server=.\SQLEXPRESS; DataBase=hhhh; Integrated Security=True;";
connection = new SqlConnection(connetionString);
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
ID = ds.Tables[0].Rows[i].ItemArray[0].ToString();
nodegroup = ds.Tables[0].Rows[i].ItemArray[1].ToString();
nodecount = ds.Tables[0].Rows[i].ItemArray[2].ToString();
sql = "insert into groups (id,nodegroup,nodecount)
values(" + ID + ",'" + nodegroup + "'," + nodecount + ")";
command = new SqlCommand(sql, connection);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
sql = "select * from groups";
command = new SqlCommand(sql, connection);
adpter.SelectCommand = command;
adpter.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
adpter.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
MessageBox.Show("Done ..تم ");
}
}
}
解决方法:
在确保表中的NodeGroup列为NVARCHAR()之后,请使用参数而不是串联,以防止SQL注入,并确保正确设置了数据类型.串联sql时,字符串文字是varchar,除非您在文字之前加上N.
sql = "insert into groups (id,nodegroup,nodecount)
values(@ID,@NodeGroup, @NodeCount)";
command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@ID", id);
command.Parameters.AddWithValue("@NodeGroup", nodegroup);
command.Parameters.AddWithValue("@NodeCroup", nodecount);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();