人生是一场不能存盘的RPG,我只能尽量多搞几个Screenshot

July 24, 2006

sql parameter的类型检查

Filed under: SQL&DB Accessing

如果在生成SQL Parameter时不指定类型会如何?

<appSettings>
<add key=”ConnectionString” value=”Server=.\SQL2k5;Database=Northwind;Integrated Security=SSPI” />
</appSettings>

string strConn = ConfigurationSettings.AppSettings[”ConnectionString”];
using (SqlConnection connection = new SqlConnection(strConn))
{
connection.Open();
string orderId = “10248′”;

string sql = “SELECT * FROM ORDERS WHERE OrderId= @OrderId”;
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add(new SqlParameter(”@OrderId” ,orderId) ); //非法的字符串
try
{
command.ExecuteNonQuery();
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
}

上面的例子中, OrderId在数据库中的类型为int, 我在生成parameter时故意
传入一个包含单引号的字符串,运行时会报错:
Conversion failed when converting the nvarchar value ‘10248′’ to data type int.

看来MS会进行数据类型检查.

Comments »

The URI to TrackBack this entry is: http://recordsome.blogsome.com/2006/07/24/p126/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham