1 package com.java1234.util;
2
3 import java.sql.DriverManager;
4
5 import com.mysql.jdbc.Connection;
6
7 /**
8 * 数据库工具类
9 * @author H_Pioneer
10 *
11 */
12
13 public class DbUtil {
14 private String dbUrl = "jdbc:mysql://localhost:3306/db_book";
15 //也可以写成private String dbUrl = "jdbc:mysql:///db_book";
16 private String dbUserName = "root";
17 private String dbPassword = "123456";
18 private String jdbcName = "com.mysql.jdbc.Driver";
19
20 /**
21 * 获取数据库连接
22 * @return
23 * @throws Exception
24 */
25 public Connection getCon()throws Exception{
26 Class.forName(jdbcName);
27 Connection con = (Connection) DriverManager.getConnection(dbUrl,dbUserName,dbPassword);//链接数据库
28 return con;
29
30 }
31
32 /**
33 * 关闭数据库连接
34 * @param con
35 * @throws Exception
36 */
37 public void closeCon (java.sql.Connection con)throws Exception {
38 if(con!=null){
39 con.close();
40 }
41 }
42
43 /**
44 *
45 * @param args
46 */
47 public static void main(String[] args) {
48 DbUtil dbUtil = new DbUtil();
49 try {
50 dbUtil.getCon();
51 System.out.println("数据库连接成功");
52 } catch (Exception e) {
53 // TODO Auto-generated catch block
54 e.printStackTrace(); //在命令行打印异常信息在程序中出错的位置及原因。
55 System.out.println("数据库连接");
56 }
57
58 }
59
60
61 }