天天看點

java mysql 數組_Java程式實作将數組元素存儲到mysql資料庫表中

目的是将數組元素一個個存儲到資料庫表中的字段中,主要是解決:我在将資料庫中的字段複雜計算後,需要把結果寫進資料庫的問題。

首先,我的數組元素個數等于表中的記錄數(不等也沒關系),添加空字段,資料類型為數組類型。

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();

}

}

}

注:以上程式已實作,如有疑問可在評論中提出。