java连接mysql数据库

在连接之前先要导入mysql-connector-java-5.1.21-bin.jar

 1 package com.student.dbc ;
 2 import java.sql.* ;
 3 public class DatabaseConnection {
 4     private static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;//mysql驱动
 5      private static final String DBURL = "jdbc:mysql://localhost:3306/java_web?useUnicode=true&characterEncoding=UTF-8" ;//数据库地址
 6     private static final String DBUSER = "root" ;//数据库用户名
 7     private static final String DBPASSWORD = "root" ;//数据库密码
 8     private Connection conn = null ;
 9     public DatabaseConnection() throws Exception{
10         try{
11             Class.forName(DBDRIVER) ;
12             this.conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD) ;
13         }catch(Exception e){
14             throw e ;
15         }
16     }
17     public Connection getConnection(){
18         return this.conn ;
19     }
20     public void close() throws Exception{
21         if(this.conn != null){
22             try{
23                 this.conn.close() ;
24             }catch(Exception e){
25                 throw e ;
26             }
27         }
28     }
29 }
原文地址:https://www.cnblogs.com/oumyye/p/4189611.html