Smart meters, designed for information collection and system monitoring in smart grid, report fine-grained power consumption to utility providers. With these highly accurate profiles of energy usage, however, it is possible to identify consumers' specific activity or behavior patterns, thereby giving rise to serious privacy concerns. In this paper, this concern is addressed by using battery energy storage. Beyond privacy protection, batteries can also be used to cut down the electricity bill. From a holistic perspective, a dynamic optimization framework is designed for consumers to strike a tradeoff between the smart meter data privacy and the electricity bill. In general, a major challenge in solving dynamic optimization problems lies in the need of the knowledge of the future electricity consumption events. By exploring the underlying structure of the original problem, an equivalent problem is derived, which can be solved by using only the current observations. An online control algorithm is then developed to solve the equivalent problem based on the Lyapunov optimization technique. To overcome the difficulty of solving a mixed-integer nonlinear program involved in the online control algorithm, the problem is further decomposed into multiple cases and the closed-form solution to each case is derived accordingly. It is shown that the proposed online control algorithm can optimally control the battery operations to protect the smart meter data privacy and cut down the electricity bill, without the knowledge of the statistics of the time-varying load requirement and the electricity price processes. The efficacy of the proposed algorithm is demonstrated through extensive numerical evaluations using real data.