去掉utf-8的Bom头:使用java以及jdbc不使用第三方库执行sql文件脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | package com.xxx.xxx.dao; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import com.ft.hsm.Util.ConstantValue; import com.ft.hsm.Util.StringUtil; /* * 使用java以及jdbc执行sql脚本的工具示例代码 */ public class SqlHelper { private static Logger logger; static { logger = Logger.getLogger(ScreenDaoImpl. class ); PropertyConfigurator.configure(ConstantValue.PATH_SCREENSERVER_LOG4J_PROPERTIES); } public static boolean createDBFromSQLFile(String SQLPath, String SQLFileCharsetName, String dbFilePath, int [] retRowsExpected) { if (StringUtil.isEmpty(SQLPath) || StringUtil.isEmpty(SQLFileCharsetName) || StringUtil.isEmpty(dbFilePath) || 0 >= retRowsExpected.length) { logger.error( "参数错误" ); return false ; } // 检验是否己创建 File dbfile = new File(dbFilePath); if (dbfile.exists() || dbfile.isDirectory()) { logger.error(dbFilePath + "数据库文件己存在或存在同名文件夹" ); return false ; } // 读取SQL文件 String sql = getText(SQLPath, SQLFileCharsetName); // "UTF-8" if (StringUtil.isEmpty(sql)) { logger.error( "读取SQL文件失败" ); return false ; } // 转换为SQL语句 List<String> sqlList = getSql(sql, SQLFileCharsetName); for ( int i = 0 ; i < sqlList.size(); i++) { logger.info(i + ":" + sqlList.get(i)); } boolean isSuccess = false ; try { // 执行SQL语句 int [] rows = SqlHelper.execute(getConn(dbFilePath), sqlList); logger.info( "Row count Expected:" + Arrays.toString(retRowsExpected)); // 执行结果集鉴定 isSuccess = Arrays.equals(rows, retRowsExpected); // 调试打印执行结果集 if ( null == rows || rows.length != retRowsExpected.length) { logger.error( "返回结果与期望个数不符, rows.length=" + rows.length + ", retRowsExpected.length=" + retRowsExpected.length); } else { for ( int index = 0 ; index < rows.length; index++) { logger.info( "rows[" + index + "] return=" + rows[index] + ", expected=" + retRowsExpected[index] + ",sql=" + sqlList.get(index)); } } } catch (Exception e) { e.printStackTrace(); } return isSuccess; } private static Connection getConn(String dbFile) { String driver = "org.sqlite.JDBC" ; // "com.mysql.jdbc.Driver"; String url = "jdbc:sqlite:" + dbFile; // "数据库连接"; // String username = "账号"; // String password = "密码"; Connection conn = null ; try { Class.forName(driver); //classLoader,加载对应驱动 conn = (Connection) DriverManager.getConnection(url /*, username, password*/ ); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } public static int [] execute(Connection conn, List<String> sqlList) throws Exception { Statement stmt = null ; stmt = conn.createStatement(); for (String sql : sqlList) { sql = sql.trim(); if (sql != null && !sql.trim().equals( "" )) stmt.addBatch(sql); } int [] rows = stmt.executeBatch(); logger.info( "Row count returned:" + Arrays.toString(rows)); conn.close(); return rows; } /* * getText方法吧path路径里面的文件按行读数来放入一个大的String里面去 * 并在换行的时候加入\r\n */ public static String getText(String path, String SQLFileCharsetName) { File file = new File(path); if (!file.exists() || file.isDirectory()) { logger.error(path + "文件不存在或存在同名文件夹" ); return null ; } StringBuilder sb = new StringBuilder(); try { FileInputStream fis = new FileInputStream(path); InputStreamReader isr = new InputStreamReader(fis, SQLFileCharsetName); BufferedReader br = new BufferedReader(isr); String temp = null ; temp = br.readLine(); while (temp != null ) { if (temp.length() >= 2 ) { String str1 = temp.substring( 0 , 1 ); String str2 = temp.substring( 0 , 2 ); if (str1.equals( "#" ) || str2.equals( "--" ) || str2.equals( "/*" ) || str2.equals( "//" )) { temp = br.readLine(); continue ; } sb.append(temp + "\r\n" ); } temp = br.readLine(); } br.close(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } /* * getSqlArray方法 * 从文件的sql字符串中分析出能够独立执行的sql语句并返回 */ public static List<String> getSql(String sql, String SQLFileCharsetName) { String s = sql; s = tryDeleteBOM(SQLFileCharsetName, s); s = s.replaceAll( "\r\n" , "\r" ); s = s.replaceAll( "\r\n" , "\r" ); s = s.replaceAll( "\r" , "\n" ); List<String> ret = new ArrayList<String>(); String[] sqlarry = s.split( ";" ); //用;把所有的语句都分开成一个个单独的句子 sqlarry = filter(sqlarry); ret = Arrays.asList(sqlarry); return ret; } public static String[] filter(String[] ss) { List<String> strs = new ArrayList<String>(); for (String s : ss) { if (s != null && !s.equals( "" )) { strs.add(s); } } String[] result = new String[strs.size()]; for ( int i = 0 ; i < strs.size(); i++) { result[i] = strs.get(i).toString(); } return result; } private static String tryDeleteBOM(String SQLFileCharsetName, String s) { byte [] byteSQL = null ; logger.info( "判断是否含有UTF-8的BOM头" ); try { byteSQL = s.getBytes(SQLFileCharsetName); // 去掉UTF-8的BOM头 if (byteSQL[ 0 ] == ( byte ) 0xef && byteSQL[ 1 ] == ( byte ) 0xbb && byteSQL[ 2 ] == ( byte ) 0xbf ) { logger.info( "含有UTF-8的BOM头" ); logger.info( "去掉UTF-8的BOM头前" + Arrays.toString(byteSQL)); s = new String(byteSQL, 3 , byteSQL.length - 3 , SQLFileCharsetName); logger.info( "去掉UTF-8的BOM头后为:" + Arrays.toString(s.getBytes(SQLFileCharsetName))); } else { logger.info( "不含有UTF-8的BOM头" ); } } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } return s; } public static void main(String[] args) { String SQLPath = "config/xxx_create.utf8.sql" ; String dbFile = "db" + File.separator + "test.db" ; String SQLFileCharsetName = "UTF-8" ; // String SQLFileCharsetName = "GBK"; int [] retRowsExpected = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 }; boolean isSuccess = createDBFromSQLFile(SQLPath, SQLFileCharsetName, dbFile, retRowsExpected); logger.info( "创建数据库" + (isSuccess ? "成功" : "失败" )); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)