Inserting Data in Java

Introduction

The database table that you will create will allow you to edit and upload information. In this article, we will discuss the process of inserting new records into an existing database. The example will also create a new database. To do this, you have to have the following prerequisites in place:

  • Must have administrative power, that is, the username and password.
  • If you are using MySQL, it should be up and running and the same goes for any other database that you will be using.

Steps to Create a new DB using JDBC application

  • The first step is to import the required packages. In this case, the java.sql.* has to be imported such that the JDBC classes can be used.
  • Next comes the registering of driver(s) to establish connections with the database.
  • Start the connection using the DriverManager.getConnection method.
  • To execute a query, you will first have to create an object of type Statement. This object will then perform the query request.
  • Once the query has been resolved, it is important to clean the environment by closing all the JDBC resources that were in use.

Example

import java.sql.*;
public class JDBCExample
{
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO Registration " + "VALUES (100, 'Ahmed', 'Shamim', 19)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES (101, 'Maesha', 'Khan', 29)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES (102, 'Varun', 'Agarwal', 39)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES(103, 'Rohan', 'Roy', 40)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
}
catch(SQLException se)
{
se.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if (stmt!=null) conn.close();
}catch(SQLException se)
{ }
try
{
if (conn!=null) conn.close();
}catch(SQLException se)
{ se.printStackTrace();
}
try
}
System.out.println("Goodbye!");
}
}

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.