import java.sql.*;
public class JdbcUtil {
public static void main(String[] args) {
Connection con = getConnection();
String sql = "select rowid from emp";
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
printRs(rs);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(rs, stmt, con);
}
}
static {// 驱动
String driverName = "oracle.jdbc.driver.OracleDriver";
try {
Class.forName(driverName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {// 连接
Connection con = null;
String url = "jdbc:oracle:thin:@localhost:1521:wish";
String user = "scott";
String pwd = "tiger";
try {
con = DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void close(ResultSet rs, Statement stmt, Connection con) {// 释放(关闭)对象
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stmt != null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void printRs(ResultSet rs) {// 数据元:任意结果集打印
if (rs == null) {
System.out.print("没有找到数据库");
return;
}
try {
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();// 获得字段个数
StringBuffer sb = new StringBuffer();
while (rs.next()) {
for (int i = 1; i <= cols; i++) {
sb.append(meta.getColumnName(i));// 字段名
sb.append("=" + rs.getString(i) + " ");// 字段值
}
sb.append("\n");
}
System.out.print(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用数据元打印任意数据
最新推荐文章于 2025-08-15 23:10:13 发布