java_JDBC连接及关闭数据库

 1 package com.java1234.jdbc.chap02.sec04;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.SQLException;
 6 
 7 
 8 public class Demo1 {
 9     //数据库地址
10     private static String dbUrl="jdbc:mysql://localhost:3306/db_book";
11     private static String dbUrl1="jdbc:mysql://localhost:3306/db_book?characterEncoding=utf8&useSSL=false";
12     //用户名
13     private static String dbUserName="root";
14     //密码
15     private static String dbPassword="shendianxin123";
16     //驱动名称
17     private static String jdbcName = "com.mysql.jdbc.Driver";
18     
19     public static void main(String[] args) {
20         try {
21             Class.forName(jdbcName);
22             System.out.println("加载驱动成功!");
23         } catch (ClassNotFoundException e) {
24             // TODO Auto-generated catch block
25             e.printStackTrace();
26             System.out.println("加载驱动失败!");
27         }
28         
29         Connection con = null;
30         try {
31             //获取数据库连接
32             con = DriverManager.getConnection(dbUrl1, dbUserName, dbPassword);
33             System.out.println("获取数据库连接成功!");
34             System.out.println("进行数据库操作!");
35         } catch (SQLException e) {
36             // TODO Auto-generated catch block
37             e.printStackTrace();
38             System.out.println("获取数据库连接失败!");
39         }finally{
40             try {
41                 con.close();
42             } catch (SQLException e) {
43                 // TODO Auto-generated catch block
44                 e.printStackTrace();
45             }
46         }
47         
48     }
49 }

 

posted @ 2017-08-12 10:02  鑫文飘雪  阅读(19388)  评论(0编辑  收藏  举报