我有一个50个字符长的字段,所以我需要做一个子字符串但是在insert命令中,但首先我要检查值是否为long,然后是子字符串这是代码的一部分,我知道这不好,所以怎么办呢?
myQuery = "INSERT INTO ERP_HEADER(IDOC_NUM,SEG_NUM,DOCTYP,HDRNUM,WHNUM,DOCNUM,DOCNOT)" +
"VALUES(" + Lidoc_num + ",'" +
SEG_NUM + "','" +
drDOK["DOCTYP"] + "'," +
drDOK["HDRNUM"] + "," +
drDOK["WHNUM"] + "," +
drDOK["DOCNUM"] + ",'" +
drDOK["DOCNOT"].ToString().Replace("'", string.Empty).Length > 50 ? Substring(0,50) + "')";
答案 0 :(得分:2)
当然,您应该仔细阅读并根据Jon Skeet的评论调整您的代码。
除此之外,您还可以编写一个小扩展方法
public static string ToShortenString(this string str, int maxLength) {
if (str == null) return null;//or string.Empty if you want to "hide" null values
return str.Substring(0, Math.Min(str.Length, maxLength));
}
然后您可以将代码更改为
drDOK["DOCNOT"].ToString().Replace("'", string.Empty).ToShortenString(50) + "')";
答案 1 :(得分:0)
myQuery = "INSERT INTO ERP_HEADER(IDOC_NUM,SEG_NUM,DOCTYP,HDRNUM,WHNUM,DOCNUM,DOCNOT)" +
"VALUES(" + Lidoc_num + ",'" +
SEG_NUM + "','" +
drDOK["DOCTYP"] + "'," +
drDOK["HDRNUM"] + "," +
drDOK["WHNUM"] + "," +
drDOK["DOCNUM"] + ",'" +
drDOK["DOCNOT"].ToString().Replace("'", string.Empty).Length > 50 ? drDOK["DOCNOT"].ToString().Substring(0,50) : drDOK["DOCNOT"].ToString() + "')";
答案 2 :(得分:0)
SqlCommand command = new SqlCommand("INSERT INTO ERP_HEADER(@IDOC_NUM,@SEG_NUM,@DOCTYP,@HDRNUM,@WHNUM,@DOCNUM,@DOCNOT)", connection);
string DOCNOT = drDOK["DOCNOT"].ToString()
if(DOCNOT.Length > 50)
DOCNOT = DOCNOT.Substring(0,50);
command.Parameters.AddWithValue("@IDOC_NUM", Lidoc_num);
command.Parameters.AddWithValue("@SEG_NUM", SEG_NUM);
command.Parameters.AddWithValue("@DOCTYP", drDOK["DOCTYP"]);
command.Parameters.AddWithValue("@HDRNUM", drDOK["HDRNUM"]);
command.Parameters.AddWithValue("@WHNUM", drDOK["WHNUM"]);
command.Parameters.AddWithValue("@DOCNUM", drDOK["DOCNUM"]);
command.Parameters.AddWithValue("@DOCNOT", DOCNOT);
command.ExecuteNonQuery();
永远不要连接sql-strings,就像要求麻烦一样。
答案 3 :(得分:0)
使用参数来避免像Jon skeet已经指出的那样注入SQL并避免语法错误:
//assuming myQuery is of type SqlCommand
myQuery = "INSERT INTO ERP_HEADER(IDOC_NUM,SEG_NUM,DOCTYP,HDRNUM,WHNUM,DOCNUM,DOCNOT)" +
"VALUES( @Lidoc_num, @SEG_NUM, @DOCTYPHDRNUM, @WHNUM, @DOCNUM, @DOCNOT)";
myquery.CommandType = CommandType.Text;
myQuery.Parameters.AddWithValue("Lidoc_num", Lidoc_num);
//...other values
myQuery.Parameters.AddWithValue("DOCNUM", drDOK["DOCNUM"]);
string DOCNOT = drDOK["DOCNOT"].ToString();
//check for your string
if(DOCNOT.Length > 50)
DOCNOT = DOCNOT.Substring(0,50);
myQuery.Parameters.AddWithValue("DOCNOT", DOCNOT);