Java_jdbc 基础笔记之一 数据库连接

来源:互联网 发布:mac字体库里灰色字体 编辑:程序博客网 时间:2024/05/16 07:25

方式一:
1、创建一个Driver实现类的对象
2、准备连接数据库的基本信息:url,user,password
3、调用Driver接口的connect(url,info)获取数据库连接

 * Driver 是一个接口:数据库厂商必须提供实现的接口,能从其中获取数据库的连接。 1.加入mysql驱动 * 1)解压mysql-connector-java-5.1.7.zip  * 2)在当前项目下新建lib目录 * 4)右键bulid-path,add to * buildpath 加入到类路径下
@Test    public void testDriver() throws SQLException {        // 1 创建Driver实现类的对象        Driver driver = new Driver();        // 2、准备连接数据库的基本信息:url,user,password        String url = "jdbc:mysql://127.0.0.1:3306/test";        Properties properties = new Properties();        properties.put("user", "root");        properties.put("password", "admin");        // 3、调用Driver接口的connect(url,properties)获取数据库连接        Connection conn = driver.connect(url, properties);        System.out.println(conn);    }运行结果如下:![程序运行结果](http://img.blog.csdn.net/20150904174143794)

方式二:
/**
* 编写一个通用的方法,在不修改源程序的情况下,可以获取任何数据库的连接
* 解决方案:把数据库驱动Driver实现类的全类名、url、user、pasword 放入一个配置文件中,
* 通过修改配置文件的方式实现和具体的数据库的解耦
*
* @throws IOException
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*
*/

public Connection getConnection() throws Exception {        String driverClass = null;        String urljdbc = null;        String user = null;        String password = null;        // 读取类路径下的jdbc.properties文件        InputStream is = getClass().getClassLoader().getResourceAsStream(                "jdbc.properties");        Properties properties = new Properties();        properties.load(is);// .....加载进来        driverClass = properties.getProperty("driver");        urljdbc = properties.getProperty("urljdbc");        user = properties.getProperty("user");        password = properties.getProperty("password");        // 通过反射创建Driver对象        Driver driver = (Driver) Class.forName(driverClass).newInstance();// 反射!!        Properties info = new Properties();        info.put("user", user);        info.put("password", password);        // 通过Driver的connect方法获取数据库的连接        Connection connection = driver.connect(urljdbc, info);        return connection;    }    @Test    public void testConnection() throws Exception {        System.out.println(getConnection());    }
0 0