標籤:
資料庫編碼 表編碼 ide編碼 必須一致,即可解決問題
情境:把這些資料匯入資料庫,並且得到城市名稱拼音的首字母
從excel中匯入資料到mysql,使用了jxl這個庫
使用了pinyin4這個庫,但是發現有bug
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Db {
static Connection connection = null;
static Statement statement = null;
public static Connection getCon() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/my?characterEncoding=UTF-8";
String uname = "root";
String pwd = "root";
connection = DriverManager.getConnection(url, uname, pwd);
statement = connection.createStatement();
} catch (ClassNotFoundException e) {
return null;
} catch (SQLException e) {
return null;
}
return connection;
}
public static void cloRes(Connection connection, Statement statement) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
connection = null;
}
}
public void add(String cityName, String cityPin) {
String sql =
"insert city (cityName,cityPin) values (‘" + cityName + "‘,‘" + cityPin + "‘)";
System.out.println(sql);
try {
statement.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import net.sourceforge.pinyin4j.PinyinHelper;
public class Input {
public static void main(String[] args) {
Db.getCon();
--------------------------------------------------------------------------------------------------------------------------------------------
測試了下面代碼 輸出sing 估計這個庫有問題
String[] s2 = PinyinHelper.toTongyongPinyinStringArray("興城".charAt(0));
System.out.println(s2[0]);
-------------------------------------------------------------------------------------------------------------------------------------------
File file = new File("city.xls");
Workbook workbook;
List<String> cities = new ArrayList<String>();
char[] cityPin = new char[700];
try {
workbook = Workbook.getWorkbook(file);
Sheet sheet = workbook.getSheet(0);
Cell[] cell = sheet.getColumn(2);
for (int i = 0; i < cell.length; i++) {
cities.add(cell[i].getContents());
}
for (int i = 0; i < cities.size(); i++) {
char cs = cities.get(i).charAt(0);
String[] s = PinyinHelper.toTongyongPinyinStringArray(cs);
cityPin[i] = s[0].charAt(0);
System.out.println(cityPin[i]);
}
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < cities.size(); i++) {
new Db().add(cities.get(i),String.valueOf(cityPin[i]));
}
Db.cloRes( Db.connection,Db.statement);
}
}
中文 資料庫 亂碼 excel中匯入資料到mysql 問題