您的位置:首页 > 数据库 > MySQL

MySQL数据库连接JDBC

2013-05-04 20:19 211 查看
1 package com.frankstyle;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 import java.sql.Statement;
 8 
 9 /**
10  * @author wang520123fan
11  *
12  */
13 public class JDBC_Connection
14 {
15     static String driverName="com.mysql.jdbc.Driver";
16     static String url="jdbc:mysql://localhost:3306/library";//需要设置自己的数据库名
17     static String username="root";
18     static String password="520123";
19     
20     static
21     {
22         try{
23             Class.forName(driverName);//通过路径来创建驱动
24             System.out.println("创建驱动成功");
25         }catch(ClassNotFoundException e)
26         {
27             e.printStackTrace();
28         }
29     }
30     
31     /**
32      * @return   返回连接
33      */
34     public static Connection getConnection()
35     {
36         Connection conn=null;
37         try{
38             conn=(Connection)DriverManager.getConnection(url,username,password);
39             System.out.println("连接数据库成功");
40         }catch(SQLException e)
41         {
42             e.printStackTrace();
43         }
44         return conn;
45     }
46     
47     /**
48      * @param conn     需要关闭的 Connection
49      * @param stmt     需要关闭的 Statement
50      * @param rs      需要关闭的 ResultSet
51      */
52     public void close(Connection conn,Statement stmt,ResultSet rs)//从内到外断开连接
53     {
54         try{
55             if(rs!=null)
56                 rs.close();
57         }catch(SQLException e)
58         {
59             e.printStackTrace();
60             System.out.println("关闭ResultSet失败!");
61         }finally
62         {
63             rs=null;
64             try{
65                 if(stmt!=null)
66                     stmt.close();
67             }catch(SQLException e)
68             {
69                 e.printStackTrace();
70                 System.out.println("关闭Statement失败!");
71             }finally
72             {
73                 stmt=null;
74                 try{
75                     if(conn!=null)
76                         conn.close();
77                 }catch(SQLException e)
78                 {
79                     e.printStackTrace();
80                     System.out.println("关闭Connection失败!");
81                 }finally
82                 {
83                     conn=null;
84                 }
85             }
86         }
87                 
88     }
89 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: