zoukankan      html  css  js  c++  java
  • java从文件中读取数据然后插入到数据库表中

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

     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();
    		}

    由于对异常捕获没有特殊要求,所以我仅仅满足了语法上的要求。。大家可以根据实际情况再做修改。

  • 相关阅读:
    【html】http状态
    【Angular】Angular基础(3)
    【Angular】Angular基础(2)
    【Angular】Angular基础(1)
    【javascript】正则表达式match、exec和test的使用
    【javascript】js实现容器Map
    【JQuery】JQuery动态查找元素
    【leetCode】4. Median of Two Sorted Arrays
    【Java】Collection,set,List,Map介绍(附实例)
    【java】String类的基本方法
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3212007.html
Copyright © 2011-2022 走看看