把jxl.jar mysql-connector-java-5.1.7-bin.jar 添加到libx下,创建数据库student 创建表stu 。
创建实体类entity
package entity;
/*
* 实体类
*/
public class Entity {
private int id;
private String name;
private String sex;
private int num;
public Entity() {
}
public Entity(int id, String name, String sex, int num) {
this.id = id;
this.name = name;
this.sex = sex;
this.num = num;
}
@Override
public String toString() {
return "StuEntity [id=" + id + ", name=" + name + ", sex=" + sex + ", num=" + num + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
创建连接数据库工具类
// 连接数据库的工具类
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcTom{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/student";
Connection con = null;
ResultSet res = null;
public void DataBase() {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, "root", "root");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.err.println("装载 JDBC/ODBC 驱动程序失败。" );
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.err.println("无法连接数据库" );
e.printStackTrace();
}
}
// 查询
public ResultSet Search(String sql, String str[]) {
DataBase();
try {
PreparedStatement pst =con.prepareStatement(sql);
if (str != null) {
for (int i = 0; i < str.length; i++) {
pst.setString(i + 1, str[i]);
}
}
res = pst.executeQuery();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
// 增删修改
public int AddU(String sql, String str[]) {
int a = 0;
DataBase();
try {
PreparedStatement pst = con.prepareStatement(sql);
if (str != null) {
for (int i = 0; i < str.length; i++) {
pst.setString(i + 1, str[i]);
}
}
a = pst.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return a;
}
}
创建业务逻辑类
package service;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import entity.Entity;
import jdbc.JdbcTom;
import jxl.Sheet;
import jxl.Workbook;
public class Service {
/**
* 查询stu表中所有的数据
*
* @return
*/
public static List<Entity> getAllByDb() {
List<Entity> list = new ArrayList<Entity>();
try {
JdbcTom db = new JdbcTom();
String sql = "select * from stu";
ResultSet rs = db.Search(sql, null);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String sex = rs.getString("sex");
int num = rs.getInt("num");
// System.out.println(id+" "+name+" "+sex+ " "+num);
list.add(new Entity(id, name, sex, num));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
/**
* 查询指定目录中电子表格中所有的数据
*
* @param file
* 文件完整路径
* @return
*/
public static List<Entity> getAllByExcel(String file) {
List<Entity> list = new ArrayList<Entity>();
try {
Workbook rwb = Workbook.getWorkbook(new File(file));
Sheet rs = rwb.getSheet("Test Shee 1");// 或者rwb.getSheet(0)
int clos = rs.getColumns();// 得到所有的列
int rows = rs.getRows();// 得到所有的行
System.out.println(clos + " rows:" + rows);
for (int i = 1; i < rows; i++) {
for (int j = 0; j < clos; j++) {
// 第一个是列数,第二个是行数
String id = rs.getCell(j++, i).getContents();// 默认最左边编号也算一列 所以这里得j++
String name = rs.getCell(j++, i).getContents();
String sex = rs.getCell(j++, i).getContents();
String num = rs.getCell(j++, i).getContents();
System.out.println("id:" + id + " name:" + name + " sex:" + sex + " num:" + num);
list.add(new Entity(Integer.parseInt(id), name, sex, Integer.parseInt(num)));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
/**
* 通过Id判断是否存在
*
* @param id
* @return
*/
public static boolean isExist(int id) {
try {
JdbcTom db = new JdbcTom();
ResultSet rs = db.Search("select * from stu where id=?", new String[] { id + "" });
if (rs.next()) {
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
/*
* List<StuEntity> all=getAllByDb(); for (StuEntity stuEntity : all) {
* System.out.println(stuEntity.toString()); }
*/
System.out.println(isExist(1));
}
}
创建sql-Excel表格测试类
package excel;
import java.io.File;
import java.util.List;
import entity.Entity;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import service.Service;
import jxl.write.Label;
/*
* 从数据库到生成Excel表格数据
*/
public class SqlToExcel {
public static void main(String[] args) {
try {
WritableWorkbook wwb = null;
// 创建可写入的Excel工作簿
String fileName = "D://book.xls";
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
// 以fileName为文件名来创建一个Workbook
wwb = Workbook.createWorkbook(file);
// 创建工作表
WritableSheet ws = wwb.createSheet("Test Shee 1", 0);
// 查询数据库中所有的数据
List<Entity> list = Service.getAllByDb();
// 要插入到的Excel表格的行号,默认从0开始
Label labelId = new Label(0, 0, "编号(id)");// 表示第
Label labelName = new Label(1, 0, "姓名(name)");
Label labelSex = new Label(2, 0, "性别(sex)");
Label labelNum = new Label(3, 0, "薪水(num)");
ws.addCell(labelId);
ws.addCell(labelName);
ws.addCell(labelSex);
ws.addCell(labelNum);
for (int i = 0; i < list.size(); i++) {
Label labelId_i = new Label(0, i + 1, list.get(i).getId() + "");
Label labelName_i = new Label(1, i + 1, list.get(i).getName());
Label labelSex_i = new Label(2, i + 1, list.get(i).getSex());
Label labelNum_i = new Label(3, i + 1, list.get(i).getNum() + "");
ws.addCell(labelId_i);
ws.addCell(labelName_i);
ws.addCell(labelSex_i);
ws.addCell(labelNum_i);
}
// 写进文档
wwb.write();
// 关闭Excel工作簿对象
wwb.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
创建Excel—SQL测试类
package excel;
import java.util.List;
import entity.Entity;
import jdbc.JdbcTom;
import service.Service;
/*
* 从Excel到数据库
*/
public class ExcelToSql {
public static void main(String[] args) {
//得到表格中所有的数据
List<Entity> listExcel=Service.getAllByExcel("D://book.xls");
/*//得到数据库表中所有的数据
List<StuEntity> listDb=StuService.getAllByDb();*/
JdbcTom db=new JdbcTom();
for (Entity stuEntity : listExcel) {
int id=stuEntity.getId();
if (!Service.isExist(id)) {
//不存在就添加
String sql="insert into stu (name,sex,num) values(?,?,?)";
String[] str=new String[]{stuEntity.getName(),stuEntity.getSex(),stuEntity.getNum()+""};
db.AddU(sql, str);
}else {
//存在就更新
String sql="update stu set name=?,sex=?,num=? where id=?";
String[] str=new String[]{stuEntity.getName(),stuEntity.getSex(),stuEntity.getNum()+"",id+""};
db.AddU(sql, str);
}
}
}
}
有的运行会出现:Field 'id' doesn't have a default value 错误
以下解决方法:
Field 'id' doesn't have a default value昨晚做项目的时候遇到一个问题,在测试数据存储的时候老是报Field 'id' doesn't have a default value异常,从网上找了好久,根据各位大虾的说法也测试了好久好久,可就是没发现原因所在,鼓捣了两三个小时的时间,最后总算找到问题所在:原来是我的数据设计的时候,把主键的类型定义为int的,原本想是用自增的方式来的,可是由于自己的粗心,写sql语句的时候没有加上auto_increment,所以在数据存储的时候老是报Field 'id' doesn't have a default value,id根本就没有值啊!!
加上自己从网上找的其他人说的他们遇到这种时候的原因,在这里总结一下:
1、打开my.ini,查找
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
修改为
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
然后重启MYSQL
2、MySQL 5 uses a strict mode which needs to be disabled.
In Windows, Goto Start-->Programs-->MySQL->MySQL Instance Config Wizard. Follow through the Reconfigure Instance option-->Detailed Configuration-->Continue Next a few screens. At the bottom under Enable TCP/IP option there is 'Enable Strict Mode'. Deslect this option (no tick). Save changes and MySQL will restart.
3、看看你的数据库定义的时候是不是把主键生成方式设置为int的,但是没有设置为自增的!!或者数据定义的时候设置一个默认值就可以了。