2016-11-22 13 views
-1

次のコードを実行すると、nullがデータベースに格納されず、代わりに空の文字列が取得されます。その周りに道があるのですか?stringBuilderを使用してmysql C#にnullを挿入します。

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

関連する問題