使用JAVA程序将EXCEL数据导入MySQL数据库问题
从网上找了一段读取EXCEL的代码,稍作修改,发现能实现功能.程序可以解析EXCEL文档,并插入数据库。
主要问题:
在SQL语句相同的情况下,有些语句插入数据库失败。但是在命令行下插入这些语句却能成功。
截图:
我的程序代码:
import java.io.File;
import
java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.swing.JOptionPane;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
/**
* 导入Excel表
* @author Administrator
* 输入数据:表路径
*/
public class TestExcel2 {
static String UserName = "job_peopleinfo"; // 生成的数据库名字
private static Connection conn = null;
private static String drive = "com.mysql.jdbc.Driver";
private static String DBurl ="jdbc:mysql://localhost:3306/xms";
private static String name = "root"; //数据库账号
private static String pwd = "root"; //数据库,密码
private static Statement st=null;
public static void main(String[] args) {
readExcel("E:/T/3.xls");
UserName = "UserName";
}
public static void readExcel(String url) {
File filename = new File(url);
Workbook wb = null;
String sql = "insert into " + UserName + "(";
String parameter = "";
String value = "";
String insert = "";
try {
wb = Workbook.getWorkbook(filename);
Sheet s = wb.getSheet(0);// 第1个sheet
Cell c = null;
int row = s.getRows();// 总行数
int col = s.getColumns();// 总列数
for (int i = 0; i < col; i++) {
if (i == col-1) {
parameter += s.getCell(i, 0).getContents();
} else {
parameter += s.getCell(i, 0).getContents() + ",";
}
}
System.out.println("--------------------------------------");
for (int i = 1; i < row; i++) {
value="";
for (int j = 0; j < col-4; j++) {
c = s.getCell(j, i);
if (j < col - 1) {
value += "'" + c.getContents() + "',";
} else {
value += "'" + c.getContents() + "'";
}
}
value += (Long)Long.parseLong(s.getCell(col-4,i).getContents()) + "," + (Long)Long.parseLong(s.getCell(col-3,i).getContents()) + "," + (Long)Long.parseLong(s.getCell(col-2, i).getContents()) + "," + (Long)Long.parseLong(s.getCell(col-1,i).getContents());