数据库自动关闭,方便多了。
代码语言:javascript复制package com.item.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCUtil implements AutoCloseable {
private static String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://127.0.0.1:3306/mytest?characterEncoding=utf-8";
// 连接对象
private static Connection conn;
// 结果集
private static ResultSet rs;
// 代码块
static{
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, "root", "12345678");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 全SQL查询
* @param sql
* @return
* @throws SQLException
*/
public static ResultSet query(String sql) throws SQLException {
return conn.createStatement().executeQuery(sql);
}
/**
* @param sql
* @return
* @throws SQLException
*/
public static int update(String sql) throws SQLException {
return conn.prepareStatement(sql).executeUpdate();
}
@Override
public void close() throws Exception {
if (null != rs) {
rs.close();
}
if (null != conn) {
conn.close();
}
}
}
数据测试:
代码语言:javascript复制 public static void main(String[] args) throws SQLException {
ResultSet re = query("select * from users");
while (re.next()) {
System.out.println(re.getObject(1));
System.out.println(re.getObject(2));
System.out.println(re.getObject(3));
System.out.println(re.getObject(4));
System.out.println(re.getObject(5));
}
}
swing
代码语言:javascript复制 /**
* 转换为Vectors集合
*
* @param userList
* @return
*/
public static Vector<Vector<String>> listToVectors(List<UserVo> userList) {
Vector<Vector<String>> datas = new Vector<Vector<String>>();
for (int i = 0; i < userList.size(); i ) {
UserVo u = userList.get(i);
if (null == u)
continue;
Vector<String> item = new Vector<String>();
item.add(u.getId().toString());
item.add(u.getAccount());
item.add(u.getSex() == 1 ? "男" : "女");
item.add(u.getEducation());
item.add(u.getPhone());
item.add(u.getEmail());
item.add(u.getRegisterDate());
if (null == u.getUpdateDate()) {
item.add("");
}else {
item.add(u.getUpdateDate());
}
datas.add(item);
}
return datas;
}
三行实现JTable数据更新。
代码语言:javascript复制datas.clear();
datas.addAll(ListDbUtils.listToVectors(userService.list()));
jTable.updateUI();
JTable jTable = new JTable(datas, heads);
这个方便快捷一些,但是javaEE的还没有测试。后面我搞个完整的就都知道了。