java将SQL文件导入到数据库

        最近在做一个CMS系统,不免会在CMS安装阶段会有一个Install database阶段,需要用到安装数据库,之前已经用mysqldunp命令到处一个sql格式的文件,现在需要将它导入数据库。由于java里没有直接针对于数据库的文件操作。只能考虑其他办法:这里是采用读取文件拼接成字符串,并批量处理(addBatch)的方式:代码如下:

private static File file = new File("E:\\data\\tulufan.sql");
	private static InputStreamReader fileReader;
	static {
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			fileReader = new InputStreamReader(new FileInputStream(file),
					"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void readSQLFile() {
		BufferedReader bufferedReader = new BufferedReader(fileReader);
		try {
			StringBuilder sBuilder = new StringBuilder("");
			String str = bufferedReader.readLine();
			while (str != null) {
				// 去掉一些注释,和一些没用的字符
				if (!str.startsWith("#") && !str.startsWith("/*")
						&& !str.startsWith("–") && !str.startsWith("\n"))
					sBuilder.append(str);
				str = bufferedReader.readLine();
			}
			String[] strArr = sBuilder.toString().split(";");
			List<String> strList = new ArrayList<String>();
			for (String s : strArr) {
				strList.add(s);
				System.out.println(s);
			}
			// 创建数据连接对象,下面的DBConnection是我的一个JDBC类
			DBConnection db = new DBConnection();
			db.executeBatchByStatement(strList);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bufferedReader.close();
				fileReader.close();
			} catch (Exception e) {
			}
		}
		return true;
	}
/*******************************
** DBConnection类中批量处理方法
*/
public boolean executeBatchByStatement(List<String> sqlList) {
		boolean ret = false;
		if (conn != null) {
			Statement stmt = null;
			try {
				conn.setAutoCommit(false);
				stmt = conn.createStatement();
				for (String s : sqlList) {
					stmt.addBatch(s);
				}
				stmt.executeBatch();
				conn.commit();
				ret = true;
			} catch (BatchUpdateException e) {
				e.printStackTrace();
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					conn.setAutoCommit(true);
					if (stmt != null) {
						stmt.close();
						stmt = null;
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return ret;
	}
    当然,这只是我个人想出来的一个办法,愚陋之见还望大家批评指教,共同提高啊。。。代码有什么问题的可以QQ我,共同商讨啊。。



  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值