本帖最后由 冯超 于 2013-3-16 15:48 编辑
- package jdbc;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- //工具类
- public final class JdbcUtils {
- private static String url = "jdbc:mysql://localhost:3306/jdbc";
- private static String user = "root";
- private static String password = "5512013025";
- private JdbcUtils() {
- }
- static {
- //注册驱动
- try {
- Class.forName("com.mysql.jdbc.Driver");
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public static Connection getConnection() throws SQLException {
- return DriverManager.getConnection(url,user,password);
- }
- public static void free(ResultSet rs, Statement st, Connection conn) {
- try {
- if(rs != null)
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- if(st != null)
- st.close();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- if(conn != null) {
- try {
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- }
复制代码- package jdbc;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class Base {
- /**
- * @param args
- * @throws ClassNotFoundException
- * @throws SQLException
- */
- public static void main(String[] args) throws SQLException, ClassNotFoundException {
- // TODO Auto-generated method stub
- //test();
- template();
- }
- //正规的jdbc码 模板如下
- @SuppressWarnings("null")
- static void template() throws SQLException
- {
- Connection conn = null;
- Statement st = null;
- ResultSet rs = null;
- try {
- // 2.建立连接
- JdbcUtils.getConnection();
- //3.创建语句
- st = conn.createStatement();
- //4.执行语句
- rs = st.executeQuery("select * from user");
- //5.处理结果
- while(rs.next()) {
- System.out.println(rs.getObject(1) + "\t" +
- rs.getObject(2) +
- rs.getObject(3) + "\t" +
- rs.getObject(4) + "\t");
-
- }
- } finally {
- JdbcUtils.free(rs, st, conn);
- }
- }
复制代码 为什么出现空指针异常
当我把他们写在一个函数的时候- public static void test() throws SQLException, ClassNotFoundException {
- //1.注册驱动
- //DriverManager.registerDriver(new com.mysql.jdbc.Driver());//方法一
- //System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");//方法二
- Class.forName("com.mysql.jdbc.Driver"); //方法三 最好
-
- //2.建立连接
- String url = "jdbc:mysql://localhost:3306/jdbc";
- String user = "root";
- String password = "5512013025";
- Connection conn = DriverManager.getConnection(url,user,password);
-
- //3.创建语句
- Statement st = conn.createStatement();
-
- //4.执行语句
- ResultSet rs = st.executeQuery("select * from user");
-
- //5.处理结果
- while(rs.next()) {
- System.out.println(rs.getObject(1) + "\t" +
- rs.getObject(2) +
- rs.getObject(3) + "\t" +
- rs.getObject(4) + "\t");
-
- }
- System.out.println("aaaaaaaaabbbbbbbbbbb");
- //释放资源
- rs.close();
- st.close();
- conn.close();
- }
复制代码 就没问题,不知道为什么? |