标签:
package app.java.anno.demo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/*
* 自定义一个注解类,用于定义连接MySQL数据库使用的四个参数.
* * driverClassName
* * url
* * username
* * password
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public@interfaceJdbcinfo{
String driverClassName()default"com.mysql.jdbc.Driver";
String url();
String username()default"root";
String password();
}
package app.java.anno.demo;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 封装利用JDBC连接MySQL数据库的工具类.
* @author JYL
*/
@Jdbcinfo(password ="root", url ="jdbc:mysql://localhost:3306/day0402")
publicclassJDBCUtils{
privatestaticJdbcinfo jdbcinfo =null;
static{
//利用反射读取对应注解信息
Class<JDBCUtils> clazz1 =JDBCUtils.class;
Class<Jdbcinfo> clazz2 =Jdbcinfo.class;
Jdbcinfo jdbcinfo = clazz1.getAnnotation(clazz2);
try{
Class.forName(jdbcinfo.driverClassName());
}catch(Exception e){
e.printStackTrace();
}
}
publicstaticConnection getConnection()throwsSQLException{
returnDriverManager.getConnection(jdbcinfo.url(),jdbcinfo.username(),jdbcinfo.password());
}
publicstaticvoid close(Connection conn,Statement stmt){
try{
if(stmt !=null){stmt.close();}
if(conn !=null){conn.close();}
}catch(SQLException e){
e.printStackTrace();
}
}
publicstaticvoid close(Connection conn,Statement stmt,ResultSet rs){
try{
if(rs !=null){rs.close();}
if(stmt !=null){stmt.close();}
if(conn !=null){conn.close();}
}catch(SQLException e){
e.printStackTrace();
}
}
}
标签:
原文地址:http://www.cnblogs.com/istarry/p/8c7046decdb083e8537709445fb3d8d2.html