Thursday, January 21, 2010

Sample Program to insert data in the database using java

package Queries;
import java.util.Scanner;
import java.sql.*;

public class InsertRoom {

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DATABASE_URL = "jdbc:mysql://localhost/doscstschedule";
static private PreparedStatement insertNewRoom = null;
static String roomCode;
static String deptCode;

public static void main(String[] args) {

Connection connection = null; // manages connection

// connect to database doscstschedule and query database
try {

Class.forName(JDBC_DRIVER); // load database driver class

// establish connection to database
connection = DriverManager.getConnection(DATABASE_URL, "root", "");
Scanner input = new Scanner(System.in);
System.out.print("Enter room code: ");
roomCode = input.next();
System.out.print("Enter department code: ");
deptCode = input.next();

// create Statement for querying database
insertNewRoom = connection.prepareStatement("insert into room values(?,?)");
insertNewRoom.setString(1, roomCode);
insertNewRoom.setString(2, deptCode);

insertNewRoom.executeUpdate();

System.out.println("Data successfully added");
} // end try
catch (SQLException sqlException) {
sqlException.getMessage();
System.exit(0);
} // end catch
catch (ClassNotFoundException classNotFound) {
classNotFound.getMessage();
System.exit(0);
} // end catch
finally // ensure statement and connection are closed properly
{
try {
insertNewRoom.close();
connection.close();
} // end try
catch (Exception exception) {
exception.getMessage();
System.exit(0);
} // end catch
} // end finally
}
}

No comments:

Post a Comment