Weather Application in Java with MySQL using OpenWeather API

Do you want to develop a Java application which fetches the current weather of any city at that exact moment and prints it on a webpage for you? Follow the underlying steps and build an application of your own.

Requirements:

  • Java IDE
  • OpenWeather API
  • XAMPP Server – for MySQL Database and Apache Server

OpenWeather API is used for fetching of weather data of different cities and adding it to the database. Java Library for OpenWeatherMap.org Weather APIs: OWM Java APIs.

DO GENERATE YOUR OWN API KEY. THE API KEY IN THE CODE IS A FAKE KEY. 
You can use any of the APIs given on OpenWeather API's website.
Prefer to use CurrentWeather API.

Apache Server and MySQL database are integrated using XAMPP Server.

Database name: city
Table name: temperature

The table contains 3 inputs which are “name” (varchar/ 30), “min” (decimal/ 15,2) and “max” (decimal/ 15,2). The default username of MySQL database is “root” and the default password is “”. 

MySQL Connector/J is the official JDBC driver for MySQL. MySQL Connector/J 8.0 is compatible with all MySQL versions starting with MySQL 5.6. The link for the connector is available here: MySQL JDBC Driver.

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import net.aksingh.owmjapis.core.OWM;
import net.aksingh.owmjapis.api.APIException;
import net.aksingh.owmjapis.model.CurrentWeather;

public class InsertData {
     
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
    //MySQL driver for JDBC 
     
    static final String DB_URL = "jdbc:mysql://localhost/city?serverTimezone=UTC";
     //Name of database: "city"
    
    static final String USER = "root";
    static final String PASS = "";
    static Connection conn = null;

  public static void main(String[] args) throws APIException {
    try {
//Connection with OpenWeather API Using API Key //DO GENERATE YOUR API KEY, THIS IS A FAKE API WEATHER KEY
OWM owm = new OWM("eCno3gLuWf2nuU4IydWY4KsETmf1UW4s"); //Array containing the cities of which temperature has to be fetched String[] a= {"London","Delhi","Moscow",""}; //Java driver for MySQL connection Class.forName("com.mysql.jdbc.Driver"); //Opening the MySQL database connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //Code to be Executed using the API object for(int i=0;i<3;i++) { CurrentWeather cwd = owm.currentWeatherByCityName(a[i]); String name= cwd.getCityName(); Double max=cwd.getMainData().getTempMax(); Double min=cwd.getMainData().getTempMin(); //For temperature to be calculated in degree Celcius max=max-273.15; min=min-273.15; System.out.println("Inserting records into the table..."); //MySQL query for inserting records java.sql.PreparedStatement pstmt = conn.prepareStatement("INSERT INTO temprature VALUES (?, ?, ?)"); pstmt.setString(1,name); //Name of the city pstmt.setDouble(2, min); //Value of minimum temperature pstmt.setDouble(3, max); //Value of maximum temperature pstmt.executeUpdate(); } System.out.println("Successfully written to database!"); } catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); } catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); } } }

 

A webpage connected directly to the MySQL database “city” shows the output. The htdocs folder contains the webpage in C:\XAMPP.

<?php
$servername = "localhost";
$username = "root";
$password = "";
//Database name "city"
$dbname = "city";


// Create connection in mysqli
$conn = mysqli_connect($servername, $username, $password, $dbname);
//Check connection in mysqli

if(!$conn){
  die("Error on the connection" .mysqli_error());
}
else
{
  echo "
  <style>
body {
  background-image: url('sky2.jpg');
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: 100% 100%;
}
</style>

<style>
h2 {text-align: center;} 
h3 {text-align: center;} 
p {text-align: center;}  
</style>
<body>

<h2>
Weather Database Connected!
</h2>
";

}

$sql = "SELECT * FROM temperature";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "
    <h3>City Name: " . $row["name"]. "</h3>
    <p>
    Minimum Temperature: " . $row["min"]. "<sup> o</sup>C<br>
    Maximum Temperature: " . $row["max"]. "<sup> o</sup>C
    </p>
    <br>";
  }
} else {
  echo "0 results";
}

echo "</body>";
$conn->close();
?>

 

There is no requirement for JSP. Just start the Apache server and MySQL database, run the Java code and then visit the PHP page in Xampp folder. Do comment in the comments box if you have any issues, I would be happy to solve them for you. Have a good day!

Leave a Reply

Your email address will not be published. Required fields are marked *