目的是将数组元素一个个存储到数据库表中的字段中,主要是解决:我在将数据库中的字段复杂计算后,需要把结果写进数据库的问题。

首先,我的数组元素个数等于表中的记录数(不等也没关系),添加空字段,数据类型为数组类型。

1、表中有ID标识,没有的可根据上篇文章(表中添加字段字段值为行编号)进行添加;

2、写Java连接mysql数据库类

Connect.java

package GPS_Data;

import java.sql.*;

import org.omg.CORBA.PUBLIC_MEMBER;

public class Connect {

public static final String url="jdbc:mysql://localhost:3306/lunwen";

public static final String name="com.mysql.jdbc.Driver";

public static final String user="root";

public static final String password="1234";

public Connection conn=null;

public PreparedStatement pst1=null;

public Connect(String sql){

try{

Class.forName(name);

conn=DriverManager.getConnection(url,user,password);

pst1=conn.prepareStatement(sql);

}catch(Exception e){

e.printStackTrace();

}

}

public void close(){

try{

this.conn.close();

this.pst1.close();

}catch (SQLException e){

e.printStackTrace();

}

}

}

3、主函数调用进行计算和存储

main.java

package GPS_Data;

import java.sql.*;

import java.util.ArrayList;

import GPS_Data.Connect;

public class Preprocess_Model {

static String sql1=null;

static String sql2=null;

static Connect mysql1=null;

static Connect mysql2=null;

static ResultSet ret1=null;

Statement stmt=null;

public static void main(String[] args) {

sql1="select * from table";

mysql1= new Connect(sql1);

ArrayListdata=new ArrayList();//初始化动态数组

try{

ret1=mysql1.pst1.executeQuery();

double Longitude=0;

double Latitude=0;

double LO1=117.20453* Math.PI / 180.0;

double LA1=39.226417* Math.PI / 180.0;

int i=0;

while (ret1.next()){

String lie3 = ret1.getString(3);

String lie4 = ret1.getString(4);

Longitude=Double.parseDouble(lie3);

Latitude=Double.parseDouble(lie4);

double R=6378137;

double LO2=Longitude* Math.PI / 180.0;

double LA2=Latitude* Math.PI / 180.0;

double b=LO1-LO2;

double a=LA1-LA2;

double sa2, sb2;

sa2 = Math.sin(a / 2.0);

sb2 = Math.sin(b / 2.0);

double d = 2 * R

* Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(LA1)

* Math.cos(LA2) * sb2 * sb2));

data.add(d);//将计算结果添加到数组中

LO1=LO2;

LA1=LA2;

}

ret1.close();

}catch(SQLException e){

e.printStackTrace();

}

try{

sql2="update table set Distance="+"?"+"where ID="+"?";//格式修改

mysql2= new Connect(sql2);

int j=0;

for(int i=1;i<=data.size();i++){

mysql2.pst1.setDouble(1,data.get(j));

mysql2.pst1.setInt(2,i);

System.out.println(data.get(j));

int ret2=mysql2.pst1.executeUpdate();

System.out.println(ret2);

j++;

}

}catch(SQLException e){

e.printStackTrace();

}

}

}

注:以上程序已实现,如有疑问可在评论中提出。

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐