通过 stringBuilder 将 null 插入 mysql C#
Insert null to mysql C# through stringBuilder
当我 运行 以下代码时,空值不会存储在数据库中,而是得到一个空字符串。有解决办法吗?
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();
}
}
替换为:
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);
}
}
当我 运行 以下代码时,空值不会存储在数据库中,而是得到一个空字符串。有解决办法吗?
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();
}
}
替换为:
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);
}
}