java读取本地txt文件并插入数据库


txt文件为sql1.txt

txt中数据格式如图所示:

代码:

public class test {
    //连接数据库
    public static Connection getConnection(String data, String user, String pwd) {

        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/" + data + "?serverTimezone=UTC&characterEncoding=UTF-8", user, pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    //插入数据库,只能为一个字段
    public static boolean insertInto(String[] str) throws NumberFormatException {
        try {
            // blog是数据库表,root是数据库用户名,password是数据库密码
            Connection conn = getConnection("blog", "root", "password");
            conn.setAutoCommit(false);
            String sql = "INSERT INTO tb_user (id,username,password,name,birthday,sex,email,phone,qq,status,create_time,update_time) VALUES (?,?,?,?,?,?,?,?,?,?,?,?);";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            for (int i = 1; i <= str.length; i++) {
                if (i==1) pstmt.setInt(1,Integer.parseInt(str[i-1]));
                //else pstmt.setString(i, str[i-1]);
                else {
                    pstmt.setString(i, (str[i-1]).substring(1,str[i-1].length()-1));
                }
//              conn.commit();
            }
            pstmt.executeUpdate();
            conn.commit();
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {

        String[] strings = readTxt("sql1.txt");
        for (String str: strings) {
            String[] split = str.split(",");
            /*boolean b = */insertInto(split);
            /*if (b) {
                System.out.println("插入成功!");
            } else {
                System.out.println("插入失败!");
            }*/
        }
        System.out.println("终于导完了");
    }

    //读取文本操作
    public static String[] readTxt(String path) {
        File file = new File(path);
        List<String> list = new ArrayList<String>();
        String[] strings = null;
        try {
            BufferedReader bw = new BufferedReader(new FileReader(file));
            String line = null;
            //因为不知道有几行数据,所以先存入list集合中
            while ((line = bw.readLine()) != null) {
                list.add(line);
            }
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //确定数组长度
        strings = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            String s = (String) list.get(i);
            strings[i] = s;
        }
        return strings;
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM