Java如何将Geometry数据写入到mysql5.7
时间: 2024-01-24 07:02:00 浏览: 255
可以使用JDBC连接mysql5.7,然后使用PreparedStatement对象将Geometry数据写入到mysql5.7,具体步骤如下:
1. 加载JDBC驱动程序:Class.forName("com.mysql.jdbc.Driver");
2. 连接mysql5.7数据库:Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
3. 创建PreparedStatement对象:PreparedStatement ps = conn.prepareStatement("insert into table_name (geometry_column) values (?)");
4. 将Geometry数据转换成byte数组:byte[] geometryBytes = geometry.toBinary();
5. 将Geometry数据设置到PreparedStatement对象中:ps.setBytes(1, geometryBytes);
6. 执行插入操作:ps.executeUpdate();
完整代码示例:
```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.vividsolutions.jts.geom.Geometry;
public class GeometryToMysql {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
String sql = "insert into table_name (geometry_column) values (?)";
PreparedStatement ps = conn.prepareStatement(sql);
// 将Geometry数据转换成byte数组
Geometry geometry = ...;
byte[] geometryBytes = geometry.toBinary();
// 将Geometry数据设置到PreparedStatement对象中
ps.setBytes(1, geometryBytes);
// 执行插入操作
ps.executeUpdate();
ps.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
阅读全文