zoukankan      html  css  js  c++  java
  • 数据库配置文件以及连接工具类编写

    1、数据库配置文件书写

       建立db.properties,书写内容如下

    //数据库驱动的名称,可以根据不同的数据库进行相应的修改
    driver=com.mysql.jdbc.Driver
    //数据库的url,字符集需要添加,否则查询数据有可能因为乱码导致查询不到
    url=jdbc:mysql://localhost:3306/shop?characterEncoding=utf-8&serverTimezone=UTC
    //数据库用户名
    user=root
    //数据库密码
    password=root
    其中url写法:
    jdbc:mysql:[]//localhost:3306/shop?参数名:参数值
    协议 子协议 主机 端口 数据库
    其他数据库url书Oracle写法:jdbc:oracle:thin:@localhost:1521:sid

    SqlServer—jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sid
    MySql—jdbc:mysql://localhost:3306/sid
    Mysql的url地址的简写形式: jdbc:mysql:///sid
    常用属性:useUnicode=true&characterEncoding=UTF-8

     2、数据库工具类编写

      新建DBUtil文件

      数据库连接步骤:

    1、读取配置文件
    2、加载数据库驱动
    3、获取数据库连接
    4、关闭数据库连接,释放资源
    /**
    * 数据库连接工具类
    */
    public class DBUtil {
    //1、读取配置文件
    //2、加载数据库驱动
    //3、获取数据库连接
    //4、关闭数据库连接,释放资源
    private static Properties properties = new Properties();
    //加载配置文件
    static {
    String path = DBUtil.class.getClassLoader().getResource("db.properties").getPath();
    try {
    properties.load(new FileInputStream(path));
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    //获得连接
    //注册驱动
    public static Connection getConn(){
    Connection connection = null;
    try {
    Class.forName(properties.getProperty("driver"));
    connection = DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("user"),properties.getProperty("password"));
    } catch (Exception e) {
    e.printStackTrace();
    }
    return connection;
    }
    //释放资源
    public static void release(Connection connection,Statement statement,ResultSet resultSet){
    //结果集
    if(resultSet != null){
    try {
    resultSet.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    //声明
    if(statement != null){
    try {
    statement.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    //连接
    if(connection !=null){
    try {
    connection.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }
    }
    
    
    
     

      

      

  • 相关阅读:
    PAIRING WORKFLOW MANAGER 1.0 WITH SHAREPOINT 2013
    Education resources from Microsoft
    upgrade to sql server 2012
    ULSViewer sharepoint 2013 log viewer
    Top 10 Most Valuable Microsoft SharePoint 2010 Books
    讨论 Setsockopt选项
    使用 Alchemy 技术编译 C 语言程序为 Flex 可调用的 SWC
    Nagle's algorithm
    Nagle算法 TCP_NODELAY和TCP_CORK
    Design issues Sending small data segments over TCP with Winsock
  • 原文地址:https://www.cnblogs.com/wuhao-0206/p/12614867.html
Copyright © 2011-2022 走看看