首先导入mysql-connector-java-5.0.8-bin.jar
1、创建配置文件jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/shop
jdbc.username=root
jdbc.password=123456
2、读取配置文件类
package com.hx.shopping.util;
import java.io.IOException;
import java.util.Properties;
public class PropUtil {
private static Properties prop = null;
public static Properties getProp(String fileName){
if(prop==null){
prop = new Properties();
try {
//PropUtil.class.getClassLoader()得到src根路径
prop.load(PropUtil.class.getClassLoader().getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
return prop;
}
}
3、连接MySQL类
package com.hx.shopping.util;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DBUtil {
static Properties prop = PropUtil.getProp("jdbc.properties");//只写等号后半部分无法识别
/*
* 加载驱动
*/
public static final String driver = prop.getProperty("jdbc.driver");
/*
* 连接数据库的URL,端口号是数据库的端口号:3306,而不是8080
*/
public static final String url = prop.getProperty("jdbc.url");
/*
* 用户名
*/
public static final String username = prop.getProperty("jdbc.username");
/*
* 密码
*/
public static final String password = prop.getProperty("jdbc.password");
/*
* 使用静态代码块加载驱动
*/
static{
try {
Class.forName(driver);
System.out.println("加载驱动成功!!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("加载驱动失败!!!");
}
}
/*
* 连接数据的方法
*/
public static Connection getConn(){
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
System.out.println("数据库连接成功!!");
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("数据库连接失败!!");
}
return conn;
}
/*
* 关闭数据库连接
*/
public static void close(Connection conn,CallableStatement cs,ResultSet rs){
try {
if(rs != null){
rs.close();
}
if(cs != null){
cs.close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* 增删改的实现
*/
public static int changeData(Object[] params,String sql){
Connection conn = null;
CallableStatement cs = null;
conn = getConn();
int num = -1;
try {
cs = conn.prepareCall(sql);
for(int i=0;i<params.length;i++){
cs.setObject((i+1), params[i]);
}
num = cs.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(cs != null){
cs.close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return num;
}
}