jdbc初学者连接
创建properties文件
jdbc.properties
文件内容:
driver=com.mysql.jdbc.Driver//驱动目录
url=jdbc:mysql://localhost:3306/dangdang//
username=root
password=root /密码
建立类 LoadProperties 装载jdbc.properties
package com.xinhua.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class LoadProperties {
public static Properties properties = new Properties();
static{
InputStream in = LoadProperties.class.getClassLoader().getResourceAsStream("jdbc.properties");
try {
properties.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getProperties(String key){
return properties.getProperty(key);
}
}
建立常量 Constant接受四个参数
package com.xinhua.constant;
import com.xinhua.utils.LoadProperties;
public class Constant {
public static String USERNAME = LoadProperties.getProperties("username");
public static String URL = LoadProperties.getProperties("url");
public static String DRIVER = LoadProperties.getProperties("driver");
public static String PASSWORD = LoadProperties.getProperties("password");
}
建立工具类DBUtils
package com.xinhua.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.xinhua.constant.Constant;
public class DBUtils {
public static Connection getConnection() {
try {
Class.forName(Constant.DRIVER);
return DriverManager.getConnection(Constant.URL, Constant.USERNAME,
Constant.PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void closeConnection(Connection connection,
PreparedStatement ps) {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closeConnection(Connection connection,
PreparedStatement ps, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
工具类一般使用static方法
该方法还未加入连接池
后续学习过程中在加入