Java中JDBC连接数据库代码

public class DBUtil {
	// 连接对象
	private Connection conn = null;
	// SQL语句处理对象
	PreparedStatement ps = null;
	// 结果集对象
	ResultSet rs = null;

	/**
	 * 连接数据库
	 * 
	 * @return Connection
	 */
	public Connection getConnection() {
		// 数据库连接基本信息
		String Driver = "com.mysql.jdbc.Driver";
		String dbName = "laozhao";
		String dbUserName = "root";
		String dbUserPwd = "";
		String url = "jdbc:mysql://localhost:3306/" + dbName
				+ "?characterEncoding=utf8";
		try {
			// 加载驱动
			Class.forName(Driver);
			// 连接
			conn = DriverManager.getConnection(url, dbUserName, dbUserPwd);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭数据库
	 */
	public void closeConnection() {
		// 判断连接不为空则关闭
		try {
			if (this.rs != null) {
				this.rs.close(); // 关闭结果集
			}
			if (this.ps != null) {
				this.ps.close(); // 关闭SQL预处理对象
			}
			if (this.conn != null) {
				this.conn.close(); // 关闭连接
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

发布了44 篇原创文章 · 获赞 28 · 访问量 10万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章