2016-11-22 3 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