[英]Parametrizing geometry sql command c# in ASP.NET, not working
I have used this string and tested it with string concatenation.But as you know it is not safe to use this to format an sql command.我已经使用过这个字符串并用字符串连接对其进行了测试。但是正如您所知,使用它来格式化 sql 命令是不安全的。
SqlCommand param = new SqlCommand();
param.CommandText = "INSERT INTO Circle (Center_Point, Circle_Data) VALUES (geometry::STGeomFromText('POINT(@center_lat @center_lng)',0),geometry::STGeomFromText('POLYGON((@polygon))',0));";
param.Parameters.Add(new SqlParameter("@center_lat", center_lat));
param.Parameters.Add(new SqlParameter("@center_lng", center_lng));
param.Parameters.Add(new SqlParameter("@polygon", polygon));
I go to parametrize the string and get the following error:我去参数化字符串并收到以下错误:
System.Data.SqlClient.SqlException (0x80131904): A .NET Framework error occurred during execution of user-defined routine or aggregate "geometry": System.FormatException: 24141: A number is expected at position 17 of the input.
System.Data.SqlClient.SqlException (0x80131904):在执行用户定义的例程或聚合“几何”期间发生 .NET Framework 错误:System.FormatException:24141:在输入的位置 17 处需要一个数字。 The input has @center_lat.
输入有@center_lat。
Looks like it hasn't put the value into the string.看起来它没有将值放入字符串中。 but when I step through the code it does indeed hold the value.
但是当我逐步执行代码时,它确实保留了价值。
What could be the problem?可能是什么问题呢?
Thanks谢谢
Thanks to Me.Name .感谢Me.Name 。 I had to add the correct assemblies to the ASP.net project, which enabled me to set the UDT type correctly.
我必须向 ASP.net 项目添加正确的程序集,这使我能够正确设置 UDT 类型。 Updated Code is below.
更新代码如下。
SqlCommand param = new SqlCommand();
SqlGeometry point = SqlGeometry.Point(center_lat,center_lng,0);
SqlGeometry poly = SqlGeometry.STPolyFromText(new SqlChars(new SqlString(polygon)),0);
param.CommandText = "INSERT INTO Circle (Center_Point, Circle_Data) VALUES (@point,@poly);";
param.Parameters.Add(new SqlParameter("@point", SqlDbType.Udt));
param.Parameters.Add(new SqlParameter("@poly", SqlDbType.Udt));
param.Parameters["@point"].UdtTypeName = "geometry";
param.Parameters["@poly"].UdtTypeName = "geometry";
param.Parameters["@point"].Value = point;
param.Parameters["@poly"].Value = poly;
For me, using MySQL geometry, I had to use the MySqlGeometry class rather than the SqlGeometry as in the answer from @SammyG对我来说,使用 MySQL 几何图形,我必须使用 MySqlGeometry 类而不是 SqlGeometry,就像@SammyG 的答案一样
parameters.Add(new
{
...
MyGeometryObject = MySqlGeometry.Parse($"POINT({point.WGS84Lon} {point.WGS84Lat})").Value,
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.