[Java] 连接数据库mysql →→→→→进入此内容的聊天室

来自 , 2021-03-26, 写在 Java, 查看 128 次.
URL http://www.code666.cn/view/f0bda020
  1. package com.java1234.util;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5.  
  6. public class DbUtil {
  7.  
  8.         private String dbUrl="jdbc:mysql://localhost:3306/db_studentInfo?characterEncoding=utf8";
  9.         private String dbUserName="root";
  10.         private String dbPassword="root";
  11.         private String jdbcName="com.mysql.jdbc.Driver";
  12.        
  13.         /**
  14.          * 获取数据库连接
  15.          * @return
  16.          * @throws Exception
  17.          */
  18.         public Connection getCon() throws Exception{
  19.                 Class.forName(jdbcName);
  20.                 Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
  21.                 return con;
  22.         }
  23.        
  24.         /**
  25.          * 关闭数据库连接
  26.          * @param con
  27.          * @throws Exception
  28.          */
  29.         public void closeCon(Connection con) throws Exception{
  30.                 if(con!=null){
  31.                         con.close();
  32.                 }
  33.         }
  34.        
  35.         public static void main(String[] args) {
  36.                 DbUtil dbUtil=new DbUtil();
  37.                 try {
  38.                         dbUtil.getCon();
  39.                         System.out.println("数据库连接成功");
  40.                 } catch (Exception e) {
  41.                         // TODO Auto-generated catch block
  42.                         e.printStackTrace();
  43.                 }
  44.         }
  45. }
  46.  

回复 "连接数据库mysql"

这儿你可以回复上面这条便签

captcha