首先新建一个配置文件(db.properties)
项目目录
配置文件db.properties的代码
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/hotel//hotel为数据库名
jdbc.username = root//用户名
jdbc.password = root//密码
MyDBUtils.Java工具类
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 使用单例模式实现工具类
*/
public class MyDBUtils {
private static String DRIVER;
private static String URL;
private static String USERNAME;
private static String PASSWORD;
private MyDBUtils() {
// TODO Auto-generated constructor stub
}
static {
try {
loadConfig();
//机器在驱动程序只需要一次即可
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static void loadConfig() {
Properties p = new Properties();
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/zyk/utils_jdbc/db.properties");
try {
p.load(is);
DRIVER =p.getProperty("jdbc.driver");
URL =p.getProperty("jdbc.url");
USERNAME =p.getProperty("jdbc.username");
PASSWORD =p.getProperty("jdbc.password");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取数据库连接
* @return 返回一个connection
*/
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void close(ResultSet rs,PreparedStatement ps,Connection conn) {
try {
if (rs!=null) rs.close();
if (ps!=null) ps.close();
if (conn!=null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
Test.Java测试类
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Test {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
conn = MyDBUtils.getConnection();
String sql = "insert into teacher values(896,'五十年代',18)";
ps = conn.prepareStatement(sql);
ps.executeUpdate(sql);
//没有返回集,第一个给参数为null
MyDBUtils.close(null, ps, conn);
}
}