本文為您舉例了DB2數據庫從從Excel中讀取數據並導入,例子的功能有兩個:一是POI讀取Excel,二是DB2數據庫的連接和SQL執行。供您參考,希望能對您有所啟迪。
您是否遇到過需要從Excel中讀取數據呢?將數據導入數據庫保存,最終可以用報表讀取數據庫並顯示,比較簡單。查了一下兩者的資料,覺的也無所謂,需要的功能比較簡單,只要能讀取Excel數據就行,最後決定使用POI,比較信任apache,使用果然很簡單,上網找了個源碼,Copy過來稍微改改就能用了。
下面附的代碼是一個Demo,功能有兩個:一是POI讀取Excel,二是DB2數據庫的連接和SQL執行。
import Java.io.FileInputStream;import
java.io.IOException;import Java.sql.Connection;
import Java.sql.DriverManager;
import Java.sql.SQLException;
import Java.sql.Statement;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class POITest {private static Connection conn = null;
private static Statement stmt = null;
private static boolean connectDB2()
{String url = "";
String username = "username";
String password = "passWord";
//加載驅動程序以連接數據庫try
{//添加類庫驅動包db2jcc.jar和db2jcc_license_cu.jarClass.forName
("com.ibm.db2.jcc.DB2Driver");
url = "JDBC:db2://192.168.0.1:50000/dbname";
//添加類庫驅動包db2Java.jar//
Class.forName("com.ibm.db2.jdbc.app.DB2Driver").newInstance();
//url = "jdbc:db2:njtcdata";
conn = DriverManager.getConnection(url,
username, passWord);stmt = conn.createStatement();}
//捕獲加載驅動程序異常catch
(ClassNotFoundException cnfex)
{System.err.println("裝載JDBC驅動程序失敗。");
cnfex.printStackTrace();return false;}
//捕獲連接數據庫異常catch (SQLException sqlex)
{System.err.println("無法連接數據庫");
sqlex.printStackTrace();//System.exit(1);
// terminate programreturn false;}return true;}
private static boolean readExcelToDB2()
{POIFSFileSystem fs = null;HSSFWorkbook wb = null;
try {fs = new POIFSFileSystem
(new FileInputStream("c:\\test.xls"));
wb = new HSSFWorkbook(fs);} catch (IOException e)
{e.printStackTrace();return false;}
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = null;HSSFCell cell = null;
String name = "";int id = 0;int rowNum,
cellNum;int i;rowNum = sheet.getLastRowNum();
for (i = 0; i <= rowNum; i++)
{row = sheet.getRow(i);
//cellNum = row.getLastCellNum();
cell = row.getCell((short) 0);
name = cell.getStringCellValue();
cell = row.getCell((short) 1);
id = (int) cell.getNumericCellValue();
String sql = "insert into TEST(ID, NAME)
values(" + id + ",'" + name + "')";
try {stmt.executeUpdate(sql);}
catch (SQLException e1) {e1.printStackTrace();
return false;}}return true;
}public static void main(String[] args)
{if (connectDB2()==true){if
(readExcelToDB2()==true)System.out.println("數據導入成功");
elseSystem.out.println("數據導入失敗");
}else{System.out.println("數據庫連接失敗");}}}