Sunday 11 May 2014

Java: Inserting a record into MySQL database table

The given method inserts an areacode object's values to the database. It is assumed that can connect to the database. If you are not able to connect to the MySQL database please visit http://pallandri.blogspot.com/2014/02/connecting-java-and-mysql-in-eclipse.html

The code assumes that you have a DBConnection class that return a database connection. If not then check the above link.

public void addAreaCode(int areaCode, String areaName)
{
db = DBConnection.getInstance();
Connection conn = db.getConnection();
PreparedStatement stmt = null;

if (conn == null)
{
inserted.setValue("Cannot get a connection to the database");
return;
}
try
{
stmt = conn.prepareStatement("INSERT INTO AREA_CODES(area_code, area_name) " + "VALUES (?,?)");

stmt.setInt(1, areaCode);
stmt.setString(2, areaName);

stmt.executeUpdate();
}
catch (SQLException e1)
{
Logger.getGlobal().severe("Error occured while adding the area code: " + e1.getMessage());
System.out.println("SQLException: " + e1.getMessage());
e1.printStackTrace();
inserted.setValue("Unable to add area code. " + e1.getMessage());
}
finally
{
try
{
DBConnection.closeConnection();
if (stmt != null)
{
stmt.close();
}
}
catch (SQLException e1)
{
Logger.getGlobal().severe("Error occured while inserting the area code: " + e1.getMessage());
System.out.println("SQLException: " + e1.getMessage());
e1.printStackTrace();
}
}
}