先导入mysql cnpm install mysql
var mysql = require(‘mysql’);
//创建连接
var connection = mysql.createConnection({
//主机地址 (默认:localhost)
host : ‘localhost’,
//用户名
user : ‘root’,
//密码
password : ‘123456’,
//在mysql中创建的数据库名
database : ‘redmine’
});
//连接到数据库
connection.connect();
//数据测试,制作数据MultiLineString,Geojson2Wkt用于将GeoJSON几何对象或字符串表示形式转换为WKT格式
官网:https://github.com/oliverroick/Geojson2Wkt
var Geojson2wkt = require(‘Geojson2Wkt’);
var testa= Geojson2wkt.convert({ “type”: “MultiLineString”, “coordinates”: [ [ [ 116.587102554917919, 34.70666396869288 ], [ 116.587058872718771, 34.706949251404346 ], [ 116.587056626362511, 34.706966916747753 ], [ 116.587048536876523, 34.706994299965935 ], [ 116.587043536652061, 34.707011231386247 ]]]});
console.log(testa);
//sql语句,testa是数据库redmine中存在的表
var sql = “insert into testa(id,shape) values(1,GeomFromText(‘MULTILINESTRING((117.58710255491792 34.70666396869288, 116.58705887271877 34.706949251404346, 116.58705662636251 34.70696691674775, 116.58704853687652 34.706994299965935, 116.58704353665206 34.70701123138625))’))”;
//查询的函数,采用的异步请求方式
connection.query(sql,function (err, result) {});
注重细节:sql语句需要用到双引号,还有数据库的数据格式问题,使用到了GeomFromText()方法,格式为MULTILINESTRING需要用到单引号。
node读取geojson文件并自动创建数据表,填入数据
var fs = require(“fs”);
var mysql = require(‘mysql’);
const SqlString = require(‘mysql/lib/protocol/SqlString’);
//创建连接
var connection = mysql.createConnection({
//主机地址 (默认:localhost)
host : ‘localhost’,
//用户名
user : ‘root’,
//密码
password : ‘123456’,
//在mysql中创建的数据库名
database : ‘redmine’
});
//连接到数据库
connection.connect();
var sql=[];
var Geojson2wkt = require(‘Geojson2Wkt’);
fs.readFile(‘data/singlepoi.geojson’, { encoding: “utf-8” }, (err, data) => {
let jsonobj = JSON.parse(data);
var arr =jsonobj.features;
var brr =[];
var crr =[];
var drr =[];
var data =[];
var k = 0;
var sqla;
for(var i=0;i<arr.length;i++){
brr[i] = arr[i].geometry;
drr[i] = arr[i].properties;
// console.log(drr);
crr[i] =Geojson2wkt.convert(brr[i]);
}
for(var j in drr[0] ){
k++;
data[k]=j;
}
// console.log(data);
var tdata= arr[0].geometry.type;
tdata =tdata.toLowerCase();
// console.log(tdata);
// console.log(data);
// sqla =“create table ‘testc’(’”+data[1] +"’ varchar(255),’"+ data[2] +"’ varchar(255),’"+data[3] +"’ varchar(255),’"+data[4] +"’ varchar(255),)";
sqla = “CREATE TABLE IF NOT EXISTS singlepoi
( "+data[1] +"
VARCHAR(100) NOT NULL, "+ data[2] +"
VARCHAR(100) NOT NULL, "+ data[3] +"
VARCHAR(100) NOT NULL, "+data[4] +"
VARCHAR(100) NOT NULL, "+data[5] +"
VARCHAR(100) NOT NULL,geometry
" + tdata +” NOT NULL)";
connection.query(sqla);
for(var t=0;t<arr.length;t++){
sql[t] =“insert into singlepoi(”+data[1]+","+data[2]+","+data[3]+","+data[4]+","+data[5]+", geometry) values(’" + drr[t][data[1]] +"’,’" + drr[t][data[2]] +"’," +"’"+ drr[t][data[3]] +"’,’" + drr[t][data[4]] +"’,"+"’"+ drr[t][data[5]]+"’" + “,GeomFromText(’”+crr[t]+"’))";
// console.log(drr[t]);
connection.query(sql[t]);
}
});