zoukankan      html  css  js  c++  java
  • JDBC 连接 MySQL 数据库

    代码如下:

    public class JdbcUtils {

    public static Connection getConnection() throws Exception {
    /**
    * 步骤:
    * 1. 声明 driver、jdbcUrl、user、password 四个变量
    * 2. 新建 jdbc.properties 配置文件,使其在不改源码情况下,变更数据库
    * 3. 获取 jdbc.properties 文件参数,利用Java反射和输入流方式获取
    * 4. Class.forName(driver);加载驱动
    * 5. 获取连接实例
    */
    String driver = null;
    String jdbcUrl = null;
    String user = null;
    String password = null;

    InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
    Properties properties = new Properties(http://www.my516.com);
    properties.load(inputStream);
    driver = properties.getProperty("driver");
    jdbcUrl = properties.getProperty("jdbcUrl");
    user = properties.getProperty("user");
    password = properties.getProperty("password");
    Class.forName(driver);
    Connection conn = (Connection) DriverManager.getConnection(jdbcUrl, user, password);
    return conn;
    }

    public static void release(Statement statement, Connection conn, ResultSet result) {
    try {
    if (statement != null) {
    statement.close();
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    try {
    if (conn != null) {
    conn.close();
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    try {
    if (result != null) {
    result.close();
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    }
        这里我写了一个Jdbc获取连接的工具类,只要调用 getConnection() 方法就可以连接成功了。注意一点:MySQL 数据库连接参数为如下(也就是上面代码中注释部分 jdbc.properties 文件内容),否则将连不上,MySQL 端口和用户名都是默认的。
    ---------------------

  • 相关阅读:
    mp3播放时间
    图片生成视频
    语音合成服务
    360p以上
    实现文字转语音功能
    字幕格式
    音频格式
    视频格式
    微信发朋友圈 -- 群营销素材同步
    FourCC
  • 原文地址:https://www.cnblogs.com/hyhy904/p/11335078.html
Copyright © 2011-2022 走看看