用jdbc连接mysql数据库的工具类:做到连接数据库,只需要修改配置文件的数据库名,自己数据库的用户名和密码,其他不用修改,测试类已经写好。
需要的jar包:
junit-4.7.jar 和jdbc的驱动包:自己在网上可以免费下载
一:java代码
package cn.lut.dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import javax.management.RuntimeErrorException;
import org.junit.Test;
public class JdbcUtils {
private static Properties props=null;
//优化代码
//因为加载文件和加载类只需要执行一次,所以就可以放在一个静态块中,执行一次
static{
//1.加载驱动文件
try {
//对properties进行初始化
InputStream in=JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
props=new Properties();
props.load(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
//加载驱动类
try {
Class.forName(props.getProperty("driverClassName"));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
public static Connection getConnect() throws SQLException, IOException{
return DriverManager.getConnection(props.getProperty("url"),props.getProperty("username"),
props.getProperty("password"));
}
@Test
public void Test() throws IOException, SQLException{
Connection con=JdbcUtils.getConnect();
System.out.println(con);
}
}
二、配置文件
dbconfig的内容:
driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/login
username=root
password=root