java 将TXT中数据插入数据库

来源:互联网 发布:网络电视看电视台软件 编辑:程序博客网 时间:2024/05/22 05:10

在TXT文本中的内容如下:

001,小红,
002,小芳,

存放位置为G:/test.txt

数据库的testInfo表中有两个字段,id,name要将TXT中的内容插入数据库

代码如下

         public static void main(String[] args) {   insert(); }
        public static void insert() {        InputStreamReader inputReader = null;        BufferedReader bufferReader = null;        OutputStream outputStream = null; try { conn = getConnection();//打开连接 try { InputStream inputStream = new FileInputStream("G:/test.txt");  //打开txt                 inputReader = new InputStreamReader(inputStream);                 bufferReader = new BufferedReader(inputReader);                  // 读取一行                  String line = null;                          StringBuffer strBuffer = new StringBuffer();                                        while ((line = bufferReader.readLine()) != null)                    {                        strBuffer.append(line+ "\n");                        String [] strs=line.split(",");                                    String sql="insert into TestInfo(id,name) values( '"+strs[0]+"','"+strs[1])";                        st = (Statement) conn.createStatement(); int count = st.executeUpdate(sql);  System.out.println("向表中插入 " + count + " 条数据");                    }                         } catch(IOException e) {  } } catch(SQLException e) { System.out.println("插入数据失败" + e.getMessage());    } }
         public static Connection getConnection() { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver");                        //连接数据库库,设置characterEncoding=UTF-8防止乱码 con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hotelATMDb?characterEncoding=UTF-8", "root", "123456");   } catch(Exception e) { System.out.println("数据库连接失败" + e.getMessage());   }  return con; } 

0 0
原创粉丝点击