2016-11-22 71 views
-1

当我运行以下代码时,null不会存储在数据库中,而是会得到一个空字符串。有没有办法解决它?通过stringBuilder将空值插入到MySQL C#

string ConnectionString = "server=localhost; password = [email protected]; user = root; database=DB "; 
     StringBuilder sCommand = new StringBuilder("INSERT INTO mytable (Name) VALUES "); 
     string A = null; 
     using (MySqlConnection mConnection = new MySqlConnection(ConnectionString)) 
     { 
      List<string> Rows = new List<string>(); 
      for (int i = 0; i < 100000; i++) 
      { 
       Rows.Add(string.Format("('{0}')", A)); 
      } 
      sCommand.Append(string.Join(",", Rows)); 
      sCommand.Append(";"); 
      mConnection.Open(); 
      using (MySqlCommand myCmd = new MySqlCommand(sCommand.ToString(), mConnection)) 
      { 
       myCmd.CommandType = CommandType.Text; 
       myCmd.ExecuteNonQuery(); 
      } 
     } 
+1

请不要这样做 - 使用参数化查询!你正在寻求SQL注入攻击! –

+0

如果你的mysql库支持,你也可以考虑使用批量插入操作。 –

+0

你的字符串生成器也没有做任何生产。 –

回答

0

替换此:

string.Format("('{0}')", A)); 

与此:

A == null ? "(null)" : string.Format("('{0}')", A)); 

更新:

使用格式:

string.Format(new SqlFormatter(), "({0}, {1})", null, A); 

其中格式化程序:

public class SqlFormatter : IFormatProvider, ICustomFormatter 
{ 
    public object GetFormat(Type formatType) 
    { 
     if (formatType == typeof(ICustomFormatter)) 
      return this; 
     else 
      return null; 
    } 

    public string Format(string format, object arg, IFormatProvider formatProvider) 
    { 
     return arg == null ? "null" : string.Format("'{0}'", arg); 
    } 
} 
+0

谢谢,这工作,但不完全是我想要的方式。因为如果我有另一个字符串像Rows.Add(string.Format(“('{0}','{1}')”,“(null)”,“Mark”)); – BigFish