如何使用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<strTmp.length();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("获取连接失败");
		}
       
	}
	}

猜你喜欢

转载自blog.csdn.net/weixin_44250364/article/details/89606018