2012-12-12 72 views
1

我想将数据插入到数据库表:我怎样才能解决这个错误的C#

myCommand.CommandText = "INSERT INTO Selectionner (IdPrestation, 
    IdPhrase, DegreUrgence,RisqueConcerne,rowguid,Cotation) " +                
    "VALUES ('" +new Guid(emp.IdPrestation) + 
    "', '" +new Guid(emp.IdPhrase)+ "', '" + 
    emp.DegreUrgence + "','" + emp.RisqueConcerne + "','" + 
    new Guid(emp.rowguid) + "','" + emp.Cotation + "')"; 

但这返回一个错误:

Guid should contain 32 digits with 4 dashes
(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).

我怎样才能解决这个问题?

+5

,不要串联SQL字符串,但使用的参数,以避免SQL注入和解析错误。我们需要以下变量的值来回答你的问题:'emp.IdPrestation','emp.IdPhrase','emp.rowguid'。你正在使用它们来初始化'GUIDs',它必须包含32个数字并且有4个破折号(错误是不言自明的,不是吗?)。 –

+0

您可以给emp.IdPrestation,emp.IdPhrase和emp.rowguid一些示例值吗? – SWeko

回答

6

一个或多个的你

emp.IdPrestation //Or 
emp.IdPhrase //Or 
emp.rowguid //Check them before creating 

是/不是GUID这就是它抛出错误的原因。

编辑:开始

如何使用Guid.TryParse()返回true,如果分析操作成功;否则,是错误的。

//How to parse safely 
Guid IdPrestation; 
Guid IdPhrase; 
Guid rowguid; 

if(Guid.TryParse(emp.IdPrestation, out IdPrestation) && 
    Guid.TryParse(emp.IdPhrase, out IdPhrase) && 
    Guid.TryParse(emp.rowguid, out rowguid)) 
{ 
    //all variables have been parse successfully 
    //Execute the sql query as follows using parameters 
} 

编辑:结束

此外,将参数传递的直接串联SQL是unsafe bad practice。相反use a parameterised query

myCommand.CommandText = "INSERT INTO yourTableName (c1, c2, ...) 
VALUES (@p1, @p2,...)"; 
myCommand.Parameters.Add(new SqlParameter("p1", valueforCol1)); 
myCommand.Parameters.Add(new SqlParameter("p2", valueforCol2)); 
... 
4

尝试使用参数化查询作为第一项改进。然后,尝试使用Guid.Parse(string s)而不是new Guid(string s)。这样,我预计会出现一个例外情况,对于不合规的字符串。

该构造函数可能有点宽容,在这种情况下,你会想快速失败,以便知道什么字段给你带来麻烦。

+0

现在,我使用'Guid.Parse(字符串s)',但同样的错误 –

+0

但是,由于解析不能完成的错误?或者Parse成功,但实际的Insert会产生异常? – dutzu

+0

@ B.M.A检查我最近的编辑。 – Kaf

1

你不能简单的字符串创建GUID,字符串必须符合的GUID

Guid originalGuid = Guid.NewGuid(); 
originalGuid.ToString("B") gets converted to {81a130d2-502f-4cf1-a376-63edeb000e9f} 

同样

"N" - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (32 digits) 
"D" - xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (32 digits separated by hyphens) 
"B" - {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} (same as "D" with addition of braces) 
"P" - (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) (same as "D" with addition of parentheses) 
"X" - {0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00.0x00}} 

的GUID本身没有格式。这只是一个价值。请注意,您可以使用NewGuid或使用guid的构造函数来创建guid。使用NewGuid,您无法控制guid的值。使用guid的构造函数,您可以控制该值。如果您已经有了guid的字符串表示形式(也许您从数据库中读取它)或者想要在开发过程中更轻松地解释guid,那么使用构造函数将非常有用。您还可以使用ParseParseExactTryParseTryParseExact方法。

所以,你可以像这样创建的GUID:

Guid g1 = Guid.NewGuid(); //Get a Guid without any control over the contents 
Guid g2 = new Guid(new string('A',32)); //Get a Guid where all digits == 'A' 
Guid g3 = Guid.Parse(g1.ToString()); 
Guid g4 = Guid.ParseExact(g1.ToString("D"),"D"); 
Guid g5; 
bool b1 = Guid.TryParse(g1.ToString(), out g5); 
Guid g6; 
bool b2 = Guid.TryParseExact(g1.ToString("D"),"D", out g6); 
相关问题