我想通过C#将txt文件里的地理位置信息添加到数据库中,由于数据库里的数据类型是geometry,总是报错。麻烦大神帮我看一下代码哪里有问题?
1;sow;7acre;'POINT(116.360413 40.008438)'
2;sow;3acre;'POINT(116.360413 40.008438)'
3;sow;4acre;'POINT(116.360413 40.008438)'
4;sow;5acre;'POINT(116.360413 40.008438)'
上面是txt文本信息
public void Button1_Click(object sender, EventArgs e)
{
string path = @"D:\db_example\a.txt";
StreamReader sr = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read), System.Text.Encoding.UTF8);
SqlConnection con = new SqlConnection("Server=localhost;user id=sa;pwd=liujiang;database=Plan");
string sql = "insert into Plan_info values (@ProjectID,@ProjectType, @TargetDo,geometry::STGeomFromText(@d,4326))";
char delimChar = ';';
string[] split = null;
string strTemp = sr.ReadLine();
while (strTemp != null)
{
split = strTemp.Split(delimChar);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("@ProjectID", SqlDbType.Int).Value = split[0];
cmd.Parameters.Add("@ProjectType", SqlDbType.VarChar).Value = split[1];
cmd.Parameters.Add("@TargetDo", SqlDbType.VarChar).Value = split[2];
//string d = split[3];
cmd.Parameters.Add("@d", SqlDbType.Text).Value = split[3];
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
Console.WriteLine(ex.Message);
}
con.Close();
strTemp = sr.ReadLine();
}
sr.Close();
}
这是报错信息 ,上网查了下,是数据类型不匹配的原因,麻烦大神们指点解决方法。
根据你提供的代码和报错信息,可以发现问题出在插入语句的geometry类型参数上。具体来说,是通过Split方法读取的txt文件中的位置信息,使用了VARCHAR类型存储到了数据库中,而实际上应该使用geometry类型存储。
下面是一个可能解决问题的修改代码:
1.修改插入语句为:
string sql = "insert into Plan_info(ProjectID,ProjectType,TargetDo,Location) values (@ProjectID,@ProjectType,@TargetDo,geometry::STGeomFromText(@d, 4326))";
其中,Location为存储位置信息的列名,使用geometry类型。
2.修改解析txt文件中的位置信息的代码:
var point = split[3].Replace("POINT(", "").Replace(")", "").Split(' ');
var d = "POINT(" + point[1] + " " + point[0] + ")";
cmd.Parameters.Add("@d", SqlDbType.Text).Value = d;
此处使用了字符串操作,将原先的格式为 "POINT(经度 纬度)" 的位置信息转换成了 "POINT(纬度 经度)" 的格式,以适应STGeomFromText方法需要的WKT格式。
希望这些修改能够解决你的问题。