码迷,mamicode.com
首页 > 数据库 > 详细

JDBC中连接MySQL数据库

时间:2016-05-07 22:09:28      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

 1 package qddx.JDBC;
 2 import java.sql.*;
 3 
 4 public class JDBC_Connection {
 5     static String driverName = "com.mysql.jdbc.Driver";//驱动名
 6     static String url="jdbc:mysql://localhost/bbs";//地址
 7     static String userName="root";//账号
 8     static String passWord = "674768166ws";//密码
 9     static {
10         try{//连接驱动
11         Class.forName(driverName);
12         }catch(ClassNotFoundException e){
13             e.printStackTrace();
14         }
15     }
16     //连接数据库
17     public static Connection getConnection(){
18         Connection conn = null;
19         try{
20         conn = (Connection)DriverManager.getConnection(url,userName,passWord);
21         System.out.println("数据库连接成功");
22         conn.setAutoCommit(false);// 设置事务不自动提交
23         }catch(SQLException e){
24             e.printStackTrace();
25         }
26         System.out.println("已经连接");
27         return conn;
28     }
29     //关闭数据库
30     public static void free(ResultSet rs,Connection conn,Statement stmt){
31         try{
32         if(rs!=null){
33             rs.close();
34             rs=null;
35         }
36         }catch(SQLException e){
37             e.printStackTrace();
38         }finally{
39             try{
40             if(conn!=null){
41                 conn.close();
42                 conn = null;
43             }
44             if(stmt !=null){
45                 stmt.close();
46                 stmt=null;
47             }
48             }catch(SQLException e){
49                 e.printStackTrace();
50             }
51         }
52     }
53     public static void main(String[] args) {
54         JDBC_Connection.getConnection();//启动
55     }
56 
57 }

 

JDBC中连接MySQL数据库

标签:

原文地址:http://www.cnblogs.com/maple-shanqiu/p/5469196.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!