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

    JDBC 测试连接数据库

    package com.xiang.lesson01;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class DBTest {
        /*
        **建立连接的五大步骤:**
    
    1. 加载(注册)数据库
    
    2. 建立链接
    
    3. 语句对象来执行SQL语句
    
    4. 处理结果集 、返回结果
    
    5. 关闭数据库、释放资源
         */
    //    private static  String URL = "jdbc:mysql://localhost:3307/webapp1?serverTimezone=utf8mb4";
    //    useSSL=false 安全连接;
        private static  String URL = "jdbc:mysql://localhost:3307/webapp1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false" ;
        private  static  String DriverClass ="com.mysql.cj.jdbc.Driver";
        private  static  String  UserName ="webapp1";
        private  static  String  PassWord ="webapp1";
        private  static  Connection connection=null;
    
        public static   Connection getConnection(){
            try {
                Class.forName(DriverClass);
                connection = DriverManager.getConnection(URL,UserName,PassWord);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return  connection;
        }
    
    //    public  void  closeRerource(Connection connection){
    //        try {
    //            connection.close();
    //        } catch (SQLException throwables) {
    //            throwables.printStackTrace();
    //        }
    //    }
    
        public static void  closeRerource(){
           if (connection != null){
               try {
                   connection.close();
               } catch (SQLException throwables) {
                   throwables.printStackTrace();
               }
           }
        }
    
        public static void main(String[] args) {
            connection = DBTest.getConnection();
            if (connection != null){
                System.out.println("连接成功");
            }else {
                System.out.println("连接失败");
            }
            closeRerource();
        }
    
    }
    
    

    导入mysql jar包

  • 相关阅读:
    如何得到运行程序的路径,以及如何得到路径的文件夹,文件名,以及类型等等信息
    STL的心得(4)运用(MFC)
    STL的心得(3)---运用(控制台)
    【Css】清除浮动,独占一行
    [Html]加链接提示
    【JS】清除子节点
    【CSS】使Div在父元素中水平居中
    [JS]回前页
    【JS】鼠标移动到链接上变手型
    【jQuery】改变控件的使能状态
  • 原文地址:https://www.cnblogs.com/d534/p/15242231.html
Copyright © 2011-2022 走看看