本节内容:
1:从数据库里查出数据,并利用iText组件,将其显示在pdf上;
开发环境:
linux平台,
MyEclipse 7.1,
mysql5.0,
所需jar包:
iText-2.0.8.jar(本来想用5.0的,但是目前的自学的资料上有些功能不支持,所有换个稳定点的);
mysql-connector-java-5.0.8-bin.jar(看附件);
首先回顾下创建数据库连接的代码:
package com.keith.DB.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBConnection {
private Connection conn = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
public DBConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/iTextTest", "root", "111111");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
/***
* 增删改 用此方法
*
* @param sql
* @param obj
* @return
* @throws SQLException
*/
public int executeUpdate(String sql, Object[] obj) throws SQLException {
ps = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
ps.setObject(i + 1, obj[i]);
}
int ri = ps.executeUpdate();
return ri;
}
/***
* 查询调用此方法
*
* @param sql
* @param obj
* @return
* @throws SQLException
*/
public ResultSet executeQuery(String sql, Object[] obj) throws SQLException {
ps = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
ps.setObject(i + 1, obj[i]);
}
rs = ps.executeQuery();
return rs;
}
/***
* 关闭数据库
*
* @throws SQLException
*/
public void close() throws SQLException {
if (conn != null) {
conn.close();
}
if (ps != null) {
ps.close();
}
if (rs != null) {
rs.close();
}
}
}
当然连接数据库有很多种写法,哪位朋友觉得自己写的比较好,最好也发表出来吧!
一个简单的数据库和表:
create database iTextTest;
use iTextTest;
create table user(
id int not null,
name varchar not null,
birthday date not null
)
insert into user values(1,"keith",1990-09-06);
下面看:如何通过Itext来获取查询后的结果(我的这个方法很笨,且目前只能支持string 类型的内容):
希望大家也能帮我如何实现其他类型的结果,或者共享下更好的方法:
package com.keith.DB;
import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.keith.DB.util.DBConnection;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
public class ITextDB {
public static final String URI = "/home/core/Desktop/itext_test/iTextDB.pdf";
public static void main(String[] args) throws SQLException {
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(URI));
document.open();
// 实例化连接数据库对象
DBConnection dbc = new DBConnection();
ResultSet rs = dbc.executeQuery("select * from user",
new Object[] {});
while (rs.next()) {
String name = rs.getString("name");
document.add(new Paragraph(name));
document.close();
}
dbc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
运行代码,看结果!