Java保存Geo数据到MySQL的参考代码
时间: 2023-10-09 17:13:40 浏览: 104
java数据库mysql连接参考代码
以下是Java保存Geo数据到MySQL的参考代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
public class GeoDataSave {
public static void main(String[] args) throws SQLException, ParseException {
Connection conn = null;
PreparedStatement ps = null;
try {
// 连接数据库
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 创建表
String createTableSql = "CREATE TABLE IF NOT EXISTS geo_data (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50), location GEOMETRY)";
ps = conn.prepareStatement(createTableSql);
ps.executeUpdate();
// 插入数据
String insertSql = "INSERT INTO geo_data (name, location) VALUES (?, ?)";
ps = conn.prepareStatement(insertSql);
// 设置参数
ps.setString(1, "test");
WKTReader reader = new WKTReader();
Geometry geometry = reader.read("POINT(116.404 39.915)");
ps.setObject(2, geometry);
// 执行插入语句
ps.executeUpdate();
System.out.println("保存成功!");
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
}
}
```
上述代码使用了JTS库来处理Geo数据,将Geo数据以WKT格式存储到MySQL中。需要在pom.xml中加入以下依赖:
```xml
<dependency>
<groupId>com.vividsolutions</groupId>
<artifactId>jts-core</artifactId>
<version>1.15.0</version>
</dependency>
```
阅读全文