- package RARSQL;
- import java.io.FileReader;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.ArrayList;
- import java.util.List;
- public class ReadAndRunSQL {
- static String sqlFile = "D:\\\\sqlFile\\\\black_list.sql";
- public static void main(String argv []){
- try {
- ReadAndRunSQL.Mysql(Read(sqlFile));
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- @SuppressWarnings("resource")
- public static List<String> Read(String sqlFile) {
- FileReader in = null;
- List<String> sqlList = new ArrayList<String>();
- char[] buff = new char[1024];
- String[] sqlArr;
- StringBuffer str = new StringBuffer();
- int count;
- try {
- in = new FileReader(sqlFile);
- while ((count = in.read(buff)) != -1) {
- str.append(new String(buff, 0, count));
- // System.out.println(String.valueOf(buff));
- }
- sqlArr = str.toString().split("(;//s*//n//r)|(;//s*//n)");
- for (int i = 0; i < sqlArr.length; i++) {
- String sql = sqlArr[i].replaceAll("--.*", "").trim();
- if (!sql.equals("")) {
- sqlList.add(sql);
- // System.out.println(sql);
- // System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
- }
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return sqlList;
- }
- public static void Mysql(List<String> sqlList) throws SQLException,
- ClassNotFoundException {
- String driver = "com.mysql.jdbc.Driver";
- String url = "jdbc:mysql://localhost:3306/gg?useUnicode=true&characterEncoding=UTF-8";
- String user = "root";
- String password = "";
- try {
- Class.forName(driver);
- Connection conn = DriverManager.getConnection(url, user, password);
- if (!conn.isClosed())
- System.out.println("Succeeded connecting to the Database!");
- Statement statement = conn.createStatement(); // statement用来执行SQL语句
- // statement.execute(s);
- for(String sql: sqlList){
- if (!statement.execute(sql)) {
- System.out.println("SUCCESS!");
- }
- }
- conn.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/1412201514222.html
来源: http://www.codesnippet.cn/detail/1412201514222.html