2021-10-31

2021-10-31,第1张

2021-10-31

连接jdbc用字符流读取txt文本

package com.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
	//定义静态属性
	private String className = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://127.0.0.1:3306/mydb";
	private String  user ="root";
	private String password = "123456";
	private ResultSet rs ;
	private PreparedStatement ps ;
	private Connection conn;
	public void getConn(){
		try {
			Class.forName(className);
		conn =DriverManager.getConnection(url, user, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	//一个关闭 *** 作
	public void close(){
			try {
				if(conn != null)conn.close();
				if(rs != null)rs.close();
				if(ps != null)ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}
	//一个修改 *** 作
	public int update(String sql,Object[] obj){
		int count = 0;
		getConn();
		try {
		ps =	conn.prepareStatement(sql);
		for (int i = 0; i < obj.length; i++) {
			ps.setObject(i+1, obj[i]);
		}
		count = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return count;
	}
	//一个查询操作
	public ResultSet query(String sql,Object[] obj){
		getConn();
		try {
		ps =	conn.prepareStatement(sql);
		for (int i = 0; i < obj.length; i++) {
			ps.setObject(i+1, obj[i]);
			
		}
		rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
}
package com.entity;

import com.db.DBUtil;

import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {
        //连接数据库
        DBUtil db= new DBUtil();
        Object [] obj={};
        BufferedReader br;

        //创建file对象

        File file = new File("我有一座恐怖屋.txt");
        br= new BufferedReader(new FileReader(file));
        String line="";
        String  title="";
        String directory="";
        int a=0;
        obj= new Object[]{null,"标题",br.readLine()};
        db.update("insert into novel values(?,?,?)",obj);
        //具体的传输方式
        while ((line=br.readLine())!=null) {
            if(line.indexOf("正文卷 第")!=-1){
                if(directory.trim().equals("")){
                    title=line;
                    continue;
                }
                obj= new Object[]{null,title,directory};
                db.update("insert into novel values(?,?,?)",obj);
                a++;
                Thread.sleep(50);
                System.out.println(title);
                System.out.println(directory);
                title=line;
                directory="";
            }else{
                directory+=line;
            }

        }
        System.out.println("共"+a+"章");

    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4970348.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-13
下一篇 2022-11-13

发表评论

登录后才能评论

评论列表(0条)

保存