您的位置:首页 > 编程语言 > Java开发

java编写购物管理系统2----JDBC连接数据库

2017-07-26 10:17 483 查看
在eclipse中,在ShopPro项目下的src

创建一个数据库连接配置文件  jdbc.properties文件

  driver=com.mysql.jdbc.Driver

  url=jdbc:mysql://localhost:3306 /shop   //数据库名

  username=root    //MYSQL数据库用户名

  password=root    //MYSQL数据库密码

在src下创建工具包com.qf.utlis

创建读取配置文件的PropertiesUtil.java类

public class PropertiesUtil {
private static Properties properties = new Properties();
static{
//设置读取的配置文件路径
try {
properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}

//得到配置文件中对应的值
public static String getValue(String key){
return properties.getProperty(key, null);
}

}

创建连接数据库的工具类DBManager.java

package com.qf.common;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import com.qf.common.PropertiesUtil;

public class DBManager {
private static String driver = PropertiesUtil.getValue("driver");
private static String url = PropertiesUtil.getValue("url");
private static String username = PropertiesUtil.getValue("username");
private static String password = PropertiesUtil.getValue("password");
static{

//加载数据库驱动
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

//获取数据库连接
public static Connection getConnection(){
try {
//返回connection
return
DriverManager.getConnection(url, username, password);
} catch ( SQLException e) {
e.printStackTrace();
}
return null;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jdbc数据库连接