package com.sxt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* jdbc工具类 jdbc java数据库连接 executeQuery – 执行查询 返回查询结果集合(select) execute –
* 执行事物,数据库,对象操作 executeUpdate – 执行更新(插入,删除,修改)返回执行了几条
*
* @author Administrator
*
*/
public class JDBCUtil {
private static String url = “jdbc:oracle:thin:@127.0.0.1:1521:orcl”;
private static String username = “scott”;
private static String userpwd = “tiger”;
private static Connection conn;
private static Statement st;
private static ResultSet rs;
static {
// 1.加载驱动(通过反射)
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
// 2.通过驱动管理器获取连接
conn = DriverManager.getConnection(url, username, userpwd);
st = conn.createStatement();
System.out.println("数据库连接成功");
} catch (Exception e) {
e.printStackTrace();
}
}
private JDBCUtil() {
}
public static int update(String sql) {
System.out.println("sql:" + sql);
// 3.通过连接获取一个声明
try {
int i = st.executeUpdate(sql);
System.out.println("更新成功:" + i);
return i;
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
st.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return 0;
}
public static ResultSet query(String sql) {
System.out.println("sql:" + sql);
try {
rs = st.executeQuery(sql);
return rs;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void close() {
try {
rs.close();
st.close();
conn.close();
System.out.println("数据库关闭成功");
} catch (SQLException e) {
e.printStackTrace();
}
}
}