Home >Database >Mysql Tutorial >MySQL数据库连接JDBC_MySQL

MySQL数据库连接JDBC_MySQL

WBOY
WBOYOriginal
2016-06-01 13:35:131179browse

bitsCN.com

 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 wang520123fan11  *12  */13 public class JDBC_Connection14 {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     static21     {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     需要关闭的 Connection49      * @param stmt     需要关闭的 Statement50      * @param rs      需要关闭的 ResultSet51      */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         }finally62         {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             }finally72             {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                 }finally82                 {83                     conn=null;84                 }85             }86         }87                 88     }89 }

 

bitsCN.com
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn