1

When I run the following code, null does not get stored in the database and instead I get an empty string. is there a way around it?

    string ConnectionString = "server=localhost; password = p@ss1234; 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();
            }
        }
4
  • 1
    please don't do this - use a parameterized query! you are asking for sql injection attacks! Commented Nov 22, 2016 at 20:53
  • you also might consider using a bulk insert operation if your mysql library supports it. Commented Nov 22, 2016 at 20:54
  • your string builder is not doing anything productive either. Commented Nov 22, 2016 at 20:54
  • I though using StringBuilder will make it faster Commented Nov 22, 2016 at 20:57

1 Answer 1

2

Replace this:

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

with this:

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

Update:

Use a formatter:

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

Where the formatter:

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, that worked, but not exactly the way I wanted it. because if I have another string like Rows.Add(string.Format("('{0}', '{1}')", "(null)", "Mark"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.