2016-11-27 49 views
0

我想从MS Access数据库中获取字符串并通过使用数据集插入到SQL Server数据库。但是我的SQL语句中的utf8字符串插入的形式如????????? - 我能对此有何看法?使用数据集发送Unicode字符串从MS Access到SQL Server

这是我的代码:

OleDbCommand cmd2 = new OleDbCommand("select * from t_about_us", con_access); 
OleDbDataAdapter da2 = new OleDbDataAdapter(cmd2); 

DataSet ds2 = new DataSet(); 
da2.Fill(ds2, "t_about_us"); 

con.Open(); 
string command2 = "insert into t_about_us(matn,see,metatag_description,metatag_keywords,metatag_author) values('" + 
      Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(ds2.Tables[0].Rows[0]["matn"].ToString())) + "','" + 
      Convert.ToInt32(ds2.Tables[0].Rows[0]["see"].ToString()) + "','" + 
      ds2.Tables[0].Rows[0]["metatag_description"].ToString() + "','" + 
      ds2.Tables[0].Rows[0]["metatag_keywords"].ToString() + "','" + 
      ds2.Tables[0].Rows[0]["metatag_author"].ToString() + "')"; 

SqlCommand cmdd2 = new SqlCommand(command2, con); 
cmdd2.ExecuteNonQuery(); 
con.Close(); 
+2

[SQL注入警报( http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 您应该**不**将您的SQL语句连接在一起 - 使用**参数化查询**避免SQL注入 –

回答

0

通过使用动态SQL建设有刺痛文字的SQL语句像'this'你是隐式转换字符串从Unicode到由使用单字节字符集SQL Server以及任何不映射到该目标字符集的Unicode字符将被替换为问号。

因此,例如,与我的SQL Server ...

cmd.CommandText = "INSERT INTO myTable (textCol) VALUES ('γιορτή')"; 
cmd.ExecuteNonQuery(); 

...将被插入为...

????t? 

...即使[textCol]定义作为NVARCHAR列。

正确的做法是使用参数化查询,像这样

cmd.CommandText = "INSERT INTO myTable (textCol) VALUES (@word)"; 
cmd.Parameters.Add("@word", System.Data.SqlDbType.NVarChar).Value = "γιορτή"; 
cmd.ExecuteNonQuery(); 
0

谢谢我的朋友最后我的代码工作,这就是答案:

OleDbCommand cmd2 = new OleDbCommand("select * from t_about_us", con_access); 
     OleDbDataAdapter da2 = new OleDbDataAdapter(cmd2); 
     DataSet ds2 = new DataSet(); 
     da2.Fill(ds2, "t_about_us"); 

     con.Open(); 
     SqlCommand cmd1 = new SqlCommand("INSERT INTO t_about_us(matn,see,metatag_description,metatag_keywords,metatag_author) VALUES (@matn,@see,@metatag_description,@metatag_keywords,@metatag_author)",con); 
     cmd1.Parameters.Add("@see", System.Data.SqlDbType.BigInt).Value = Convert.ToInt32(ds2.Tables[0].Rows[0]["see"].ToString()); 
     cmd1.Parameters.Add("@matn", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["matn"].ToString(); 
     cmd1.Parameters.Add("@metatag_description", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_description"].ToString(); 
     cmd1.Parameters.Add("@metatag_keywords", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_keywords"].ToString(); 
     cmd1.Parameters.Add("@metatag_author", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_author"].ToString(); 
     cmd1.ExecuteNonQuery(); 
     con.Close();