这是我在优快云发飙的第一个博客,请大家多多关照!
希望能在这里多多交流java的技术!
先献丑一下!
jdbc连接技术
1:建立一个db.properties文件
内容如下:
className=com.mysql.jdbc.driver:
url=jdbc:mysql://localhost:3306/mydatabase
username=root
pwd=root
2:建立一个DBUtil.java
public class DBUtil{
//建立一个Properties对象,用来加载db.properties文件里的内容。
private static Properties prop = new Properties();
static{
InputStream ips = DBUtil.class.getClassLoader().getResourceAsStream("util/db.properties");
try {
props.load(ips);
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取db.properties文件失败");
}
}
private static String className =props.getProperty("classname");
private static String url = props.getProperty("url");
private static String username = props.getProperty("username");
private static String pwd = props.getProperty("pwd");
/**
* 获得一个连接
* @throws SQLException
*/
public static Connection getConnection() throws SQLException{
Connection conn = null;
try {
Class.forName(className);
conn = DriverManager.getConnection(
url,username,pwd);
} catch (ClassNotFoundException e) {
//记日志
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
throw e;
}
return conn;
}
/**
*
* 关闭连接
*/
public static void close(Connection conn){
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}