jdbc连接数据库方式

1.jdbc连接数据库

public class mysqlConnector {

	private Connection conn;
	private String driver="com.mysql.jdbc.Driver";
	private String url="jdbc:mysql://localhost:3306/test";
	private String username="root";
	private String password="123456";
	
	public Connection getConnection(){
		try {
			//加载驱动
			Class.forName(driver);
			conn=DriverManager.getConnection(url, username, password);
			if(conn!=null){
				System.out.println("** mysql连接成功 **");
			}
			else{
				System.out.println("** mysql连接失败 **");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
}
2.使用properties配置文件连接mysql数据库

1)创建db.properties配置文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/userdatabase
username=root
password=123456
2)创建jdbcutil工具类,读取properties配置文件信息,连接mysql数据库

public class jdbcUtil {

	public Connection conn;
	private String driver;
	private String url;
	private String user;
	private String password;

	/**
	 * 连接mysql数据库
	 * @return
	 */
	public Connection getconnection() {
		// 读取db.properties配置文件
		InputStream input = this.getClass().getResourceAsStream("/db.properties");
		Properties ps = new Properties();
		try {
			// 加载db.properties配置文件
			ps.load(input);
			driver = ps.getProperty("driver");
			url = ps.getProperty("url");
			user = ps.getProperty("username");
			password = ps.getProperty("password");
			// 加载驱动
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);
			if (conn != null) {
				System.out.println("mysql连接成功...");
			} else {
				System.out.println("mysql连接失败...");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭mysql数据库连接
	 * @param conn
	 * @param pstmt
	 * @param rs
	 */
	public static void close(Connection conn, PreparedStatement pstmt,ResultSet rs) {

		try {
			if (conn != null) {
				conn.close();
			}
			if (pstmt != null) {
				pstmt.close();
			}
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值