考慮到上述因素,那么我就在src/test/java文件夾下新建一個測試類,那么這個測試類就會在clean install時候會執行,那么在這個時候執行數據初始化是合適的。因為初始化數據來自于sql腳本,所以我得讀取sql腳本的內容并解析成相關的sql語句通過java的jdbc執行sql語句。那就開始做吧。不多說,上代碼:
1 package com.infopatent.juangetljc.core;
2
3 import java.io.BufferedReader;
4 import java.io.FileInputStream;
5 import java.io.InputStream;
6 import java.sql.Connection;
7 import java.sql.DriverManager;
8 import java.sql.SQLException;
9 import java.sql.Statement;
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.List;
13
14 import org.junit.Test;
15
16 import junit.framework.TestCase;
17
18 public class InitDataTest extends TestCase {
19
20 private String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
21 private String driver = "com.mysql.jdbc.Driver";
22 private String userName = "root";
23 private String password = "";
24 String filePathIn = "F://workspace/juange-tljc/juange-tljc-core/src/test/java/basedata.sql";
25
26 @Test
27 public void test() {
28
29 try {
30 execute(filePathIn);
31 } catch (Exception e) {
32 // TODO Auto-generated catch block
33 e.printStackTrace();
34 }
35 }
36
37 /*
38 * 讀取sql文件,獲取sql語句
39 * 返回所有sql語句的list集合
40 * */
41 private List<String> loadSql(String sqlFile) throws Exception {
42 List<String> sqlList = new ArrayList<String>();
43 /*
44 * 讀取文件的內容并寫道StringBuffer中去
45 * */
46 InputStream sqlFileIn = new FileInputStream(sqlFile);
47 StringBuffer sqlSb = new StringBuffer();
48 byte[] buff = new byte[sqlFileIn.available()];
49 int byteRead = 0;
50 while((byteRead = sqlFileIn.read(buff)) != -1) {
51 sqlSb.append(new String(buff, 0, byteRead));
52 }
53 /*
54 * windows下換行是/r/n,Linux下是/n,
55 * 此處需要根據導出的sql文件進行具體的處理,我在處理的時候
56 * 也遇到了很多的問題,如果我這個不行可以在網上找找別的解析方法
57 * */
58 String sqlArr[] = sqlSb.toString().split("(;\\s*\\rr\\n)|(;\\s*\\n)");
59 for(int i = 0; i<sqlArr.length; i++) {
60 String sql = sqlArr[i].replaceAll("--.*", "").trim();
61 if(!"".equals(sql)) {
62 sqlList.add(sql);
63 }
64 }
65 return sqlList;
66
67 }
68
69 /*
70 * 傳入文件執行sql語句
71 *
72 * */
73 private void execute(String sqlFile) throws SQLException {
74 Statement stmt = null;
75 List<String> sqlList = new ArrayList<String>();
76 Connection conn = getConnection();
77 try {
78 sqlList = loadSql(sqlFile);
79 conn.setAutoCommit(false);
80 stmt = conn.createStatement();
81 for (String sql : sqlList) {
82 System.out.println(sql);
83 stmt.addBatch(sql);
84 }
85 int[] rows = stmt.executeBatch();
86 System.out.println("Row count:" + Arrays.toString(rows));
87 conn.commit();
88 System.out.println("數據更新成功");
89 } catch (Exception e) {
90 e.printStackTrace();
91 conn.rollback();
92 }finally{
93 stmt.close();
94 conn.close();
95 }
96
97 }
98
99 /*
100 * 獲取sql連接
101 * */
102 private Connection getConnection(){
103 Connection conn = null;
104 try {
105 Class.forName(driver);
106 conn = DriverManager.getConnection(url, userName, password);
107 if(!conn.isClosed()) {
108 System.out.println("數據庫連接成功!");
109 }
110 } catch (Exception e) {
111 e.printStackTrace();
112 }
113 return conn;
114 }
115 }
116
2
3 import java.io.BufferedReader;
4 import java.io.FileInputStream;
5 import java.io.InputStream;
6 import java.sql.Connection;
7 import java.sql.DriverManager;
8 import java.sql.SQLException;
9 import java.sql.Statement;
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.List;
13
14 import org.junit.Test;
15
16 import junit.framework.TestCase;
17
18 public class InitDataTest extends TestCase {
19
20 private String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
21 private String driver = "com.mysql.jdbc.Driver";
22 private String userName = "root";
23 private String password = "";
24 String filePathIn = "F://workspace/juange-tljc/juange-tljc-core/src/test/java/basedata.sql";
25
26 @Test
27 public void test() {
28
29 try {
30 execute(filePathIn);
31 } catch (Exception e) {
32 // TODO Auto-generated catch block
33 e.printStackTrace();
34 }
35 }
36
37 /*
38 * 讀取sql文件,獲取sql語句
39 * 返回所有sql語句的list集合
40 * */
41 private List<String> loadSql(String sqlFile) throws Exception {
42 List<String> sqlList = new ArrayList<String>();
43 /*
44 * 讀取文件的內容并寫道StringBuffer中去
45 * */
46 InputStream sqlFileIn = new FileInputStream(sqlFile);
47 StringBuffer sqlSb = new StringBuffer();
48 byte[] buff = new byte[sqlFileIn.available()];
49 int byteRead = 0;
50 while((byteRead = sqlFileIn.read(buff)) != -1) {
51 sqlSb.append(new String(buff, 0, byteRead));
52 }
53 /*
54 * windows下換行是/r/n,Linux下是/n,
55 * 此處需要根據導出的sql文件進行具體的處理,我在處理的時候
56 * 也遇到了很多的問題,如果我這個不行可以在網上找找別的解析方法
57 * */
58 String sqlArr[] = sqlSb.toString().split("(;\\s*\\rr\\n)|(;\\s*\\n)");
59 for(int i = 0; i<sqlArr.length; i++) {
60 String sql = sqlArr[i].replaceAll("--.*", "").trim();
61 if(!"".equals(sql)) {
62 sqlList.add(sql);
63 }
64 }
65 return sqlList;
66
67 }
68
69 /*
70 * 傳入文件執行sql語句
71 *
72 * */
73 private void execute(String sqlFile) throws SQLException {
74 Statement stmt = null;
75 List<String> sqlList = new ArrayList<String>();
76 Connection conn = getConnection();
77 try {
78 sqlList = loadSql(sqlFile);
79 conn.setAutoCommit(false);
80 stmt = conn.createStatement();
81 for (String sql : sqlList) {
82 System.out.println(sql);
83 stmt.addBatch(sql);
84 }
85 int[] rows = stmt.executeBatch();
86 System.out.println("Row count:" + Arrays.toString(rows));
87 conn.commit();
88 System.out.println("數據更新成功");
89 } catch (Exception e) {
90 e.printStackTrace();
91 conn.rollback();
92 }finally{
93 stmt.close();
94 conn.close();
95 }
96
97 }
98
99 /*
100 * 獲取sql連接
101 * */
102 private Connection getConnection(){
103 Connection conn = null;
104 try {
105 Class.forName(driver);
106 conn = DriverManager.getConnection(url, userName, password);
107 if(!conn.isClosed()) {
108 System.out.println("數據庫連接成功!");
109 }
110 } catch (Exception e) {
111 e.printStackTrace();
112 }
113 return conn;
114 }
115 }
116
在這個過程中遇到了很多的問題,曾經一度使我陷入迷糊狀態中,后來好好梳理了一下思路,一個一個的去排查問題終于成功了~
首先在讀取文件的時候,發現讀取的文件內容顯示是正常的不是亂碼,但是插入到數據庫中就是亂碼,好吧,我又遇到了這種問題,我依次檢查了我java文件的編碼,數據庫的編碼,都設置為utf-8,url也加上編碼"jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"。結果還是亂碼,那就再看看mysql下的my.ini文件中的編碼設置在[mysqld]節點下加上default-character-set=utf8(如果沒有就改為utf8),這下終于不是亂碼了。然后我開始maven clean install,去查看數據庫發現又出現了亂碼的問題,真是折磨人啊,我發現唯一不同的就是之前正常的插入數據是我在測試類下run as junit,而現在用的是maven clean install,剛接觸maven完全不知道癥結所在啊,百度一下,發現maven構建到特定的生命周期時候運行測試用例是依靠maven-surefire-plugin這個插件的,而這個插件也需要指定字符集編碼的,于是我在項目的pom.xml中加入了如下代碼(本來竟然沒有!):
1 <build>
2 <plugins>
3 <plugin>
4 <groupId>org.apache.maven.plugins</groupId>
5 <artifactId>maven-surefire-plugin</artifactId>
6 <version>2.7.2</version>
7 <configuration>
8 <forkMode>once</forkMode>
9 <argLine>-Dfile.encoding=UTF-8</argLine>
10 <systemProperties>
11 <property>
12 <name>net.sourceforge.cobertura.datafile</name>
13 <value>target/cobertura/cobertura.ser</value>
14 </property>
15 </systemProperties>
16 </configuration>
17 </plugin>
18 </plugins>
19 </build>
2 <plugins>
3 <plugin>
4 <groupId>org.apache.maven.plugins</groupId>
5 <artifactId>maven-surefire-plugin</artifactId>
6 <version>2.7.2</version>
7 <configuration>
8 <forkMode>once</forkMode>
9 <argLine>-Dfile.encoding=UTF-8</argLine>
10 <systemProperties>
11 <property>
12 <name>net.sourceforge.cobertura.datafile</name>
13 <value>target/cobertura/cobertura.ser</value>
14 </property>
15 </systemProperties>
16 </configuration>
17 </plugin>
18 </plugins>
19 </build>
這個時候再去maven clean install,終于不亂碼了,終于不亂碼了!花了我四個小時,長見識了!此處記錄自己遇到的問題以及如何解決,希望對各位有幫助!