使用Logstash导入CSV到PostgreSQL时遇PSQL语法错误求助
问题解决:Logstash导入CSV到PostgreSQL时的SQL语法错误
错误原因
你在JDBC输出的statement中直接使用%{inputdata}这种Logstash字段引用方式,PostgreSQL无法识别%开头的语法,同时直接拼接字段值会导致SQL语句格式错误(比如字符串类型的值没有被单引号包裹),从而触发语法错误。
修复方案
优先使用参数绑定的方式,既避免语法错误,也防止SQL注入风险,修改output部分的JDBC配置如下:
output { jdbc { connection_string => "jdbc:postgresql://hostname:5432/database" username => "username" password => "password" driver_jar_path => "C:/Users/Downloads/lib/postgresql-42.5.1.jar" driver_class => "org.postgresql.Driver" # 使用?作为参数占位符 statement => "INSERT INTO csv_to_postgresql (inputdata,metric,source_table,output_column_alias,method) VALUES (?, ?, ?, ?, ?)" # 绑定Logstash字段到对应参数 parameters => { "inputdata" => "%{inputdata}" "metric" => "%{metric}" "source_table" => "%{source_table}" "output_column_alias" => "%{output_column_alias}" "method" => "%{method}" } } }
额外检查项
- 确认PostgreSQL中
csv_to_postgresql表已创建,且字段名、数据类型与CSV中的字段完全匹配 - 确保Logstash有读取CSV文件的权限,以及连接PostgreSQL数据库的权限
- 验证
postgresql-42.5.1.jar驱动版本与你的PostgreSQL服务器版本兼容
内容的提问来源于stack exchange,提问作者Mahendra kanoujiya
相关产品推荐
相关产品推荐

