java将mysql数据写入到txt_如何使用Java程序在TXT文本中分离出数据并分组插入到MySQL数据库...

将TXT文本分离出来的数据写入到MySQL表格中

前段时间帮同学写了一段程序,在TXT文本中分离出纯数据并写入到新的TXT文本中,后来突发奇想,能否把分离出的数据写入到数据库

当然,没有什么事情是实现不了的

首先要解决三个难题:

1.怎样在汉字和数字混合的文本中把数字提取出来

2.怎样把提取出来的一堆数字分组

3.怎样把数据以变量的形式写入到MySQL表格

懒得写字了,直接上程序吧

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.InputStreamReader;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class MainTest{

public static void main(String[] args) throws ClassNotFoundException, SQLException {

final String url = "jdbc:mysql://127.0.0.1:3306/day07"; //连接数据库

final String name = "com.mysql.jdbc.Driver"; //加载数据库驱动

final String user = "root"; //数据库用户名

final String password = "root"; //密码

String s1 = "";

String s2="";

String s3="";

int num=0;

String filePath = "I://Test//test.txt"; //TXT文档路径

FileInputStream fin = null;

Connection conn = null;

Class.forName(name);//指定连接类型

conn = DriverManager.getConnection(url, user, password);//获取连接

if (conn!=null) {

System.out.println("获取连接成功");

Statement stat = conn.createStatement();

try {

fin = new FileInputStream(filePath);

} catch (FileNotFoundException e1) {

// TODO 自动生成的 catch 块

e1.printStackTrace();

}

InputStreamReader reader = new InputStreamReader(fin);

BufferedReader buffReader = new BufferedReader(reader);

String strTmp = "";

try {

while((strTmp = buffReader.readLine())!=null){

num++;

strTmp=strTmp.trim();

String str2="";

String str3="";

double b = 0;

if(strTmp != null && !"".equals(strTmp)){

for(int i=0;i

if(strTmp.charAt(i)>=48 && strTmp.charAt(i)<=57){

str2+=strTmp.charAt(i);

if(str2 != null && !"".equals(str2)){

str3 = str2.substring(1, str2.length());}

try{

b = Double.parseDouble(str3);

b/=10;

} catch (Exception e) {

}

}

}

}

if(num%5==1){

s1=String.valueOf(b);

}

else if(num%5==2){

s2=String.valueOf(b);}

else if(num%5==3){

s3=String.valueOf(b);}

if(num%5==0)

stat.addBatch("insert into ysb(Temp,Humi,PH) values('"+s1+"','"+s2+"','"+s3+"')");

System.out.println(str3);

}

} catch (Exception e) {

// TODO 自动生成的 catch 块

e.printStackTrace();

}

}else {

System.out.println("获取连接失败");

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值