java从文件中读取数据然后插入到数据库表中

来源:互联网 发布:淘宝药品评价语50字 编辑:程序博客网 时间:2024/05/16 01:23

实习工作中,完成了领导交给的任务,将搜集到的数据插入到数据库中,代码片段如下:

 static Connection getConnection()throws SQLException, IOException , ClassNotFoundException{Properties props = new Properties();FileInputStream in = new FileInputStream("company.ini");props.load(in);in.close();String driver=props.getProperty("driver");String url = props.getProperty("url");String user = props.getProperty("user");String pass = props.getProperty("pass");// 加载数据库驱动Class.forName(driver);// 取得数据库连接return DriverManager.getConnection(url, user, pass);}

这个是JDBC获取数据库连接的代码,数据库的配置信息写在了company.ini文件中。

下面是从指定文件中读取数据,插入到数据库中指定表格的代码。

try{BufferedReader br=new BufferedReader(new FileReader("data.txt"));String line=null;while((line=br.readLine())!=null){String date=new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());String sql="insert into keyword_garbage values(null,'"+line+"','"+Insert.keywordEncode(line)+"',0,0,'"+date+"',null)";try{stmt.executeUpdate(sql);}catch (SQLException e2){e2.printStackTrace();}}}catch(FileNotFoundException e2){e2.printStackTrace();}catch(IOException e2){e2.printStackTrace();}
由于对异常捕获没有特殊要求,所以我仅仅满足了语法上的要求。。大家可以根据实际情况再做修改。

原创粉丝点击