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

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

 

 

posted @ 2013-07-24 20:14  爱生活,爱编程  阅读(1593)  评论(0编辑  收藏  举报