zoukankan      html  css  js  c++  java
  • 自定义JDBC工具类

    步:创建JDBC工具类

    package lo.utils;
    
    import java.sql.*;
    import java.util.UUID;
    
    /**
     * JDBC 工具类
     * @author pengYi
     *
     */
    public class JDBCUtils{
    public static Connection connection = null; public static PreparedStatement preparedStatement = null; public static ResultSet resultSet = null; /** * 连接数据库 * @return */ public static Connection getConnection(){ String url = "jdbc:mysql://localhost:3306/chartroom"; String user = "root"; String password = "root"; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(url, user, password); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return connection; } /** * 关闭资源 */ public static void close(){ try{ if(connection != null){ connection = null; connection.close(); } if(preparedStatement != null){ preparedStatement = null; preparedStatement.close(); } if(resultSet!= null){ resultSet = null; resultSet.close(); } }catch(SQLException e){ e.printStackTrace(); } } }

      第二步:工具类的使用

    package lo.utils;
    
    import java.sql.SQLException;
    import java.util.UUID;
    
    public class Dao extends JDBCUtils{
    	
    	public void insert(String string, String string2, String string3) {
    		JDBCUtils.getConnection();
    		String sql="insert into user value(?,?,?,?)";
    		try {
    			preparedStatement = connection.prepareStatement(sql);
    			preparedStatement.setString(1, UUID.randomUUID().toString().replace("-",""));
    			preparedStatement.setString(2, string);
    			preparedStatement.setString(3, string2);
    			preparedStatement.setString(4, string3);
    			preparedStatement.executeUpdate();
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		JDBCUtils.close();
    	}
    }
    

      

    总结分析:

      1.采用继承的方式使用工具类。

      2.在工具类中将需要重复用到的代码写在一个方法里面。

      3.Connection、prepareStatement、ResultSet 三个对象定义成 静态共有方便是为了方法去用,就不用每个dao里面都new三个对象。

  • 相关阅读:
    如何导入文件夹在项目中
    KVC的学习
    ScrollView学习01
    KVO与KVC整理资料
    KVO监听者
    进程与线程
    解决SQL 2008数据库日志文件过大导致占满整个分区的问题:清理数据库日志文件
    SharePoint开发中发现的SharePoint本身的一些问题
    从十个方面提升SharePoint网站性能
    解决SharePoint2010文档库中新建文档不是保存到文档库而是保存到本地电脑的问题
  • 原文地址:https://www.cnblogs.com/py1994/p/6645971.html
Copyright © 2011-2022 走看看