This article will discuss the process of Creating Database Tables using a JDBC application.
Table of Contents
Prerequisites
- You need to have administrative authority such that you have available to you, both the username and the password.
- The database that you will use should already be installed and functional.
Steps
- 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 of Creating a Table
import java.sql.*; public class JDBCExample { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; // Database credentials 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("Creating table in given database..."); stmt = conn.createStatement(); String sql = "CREATE TABLE REGISTRATION " + "(id INTEGER not NULL, " + " first VARCHAR(255), " + " last VARCHAR(255), " + " age INTEGER, " + " PRIMARY KEY ( id ))"; stmt.executeUpdate(sql); System.out.println( "Created table in given database..." ); }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 (); } } System.out.println (" Goodbye! "); } }
OUTPUT
C:\>java JDBCExample
Connecting to a selected database…
Connected database successfully…
Creating table in given database…
Created table in given database…
Goodbye!
C:\>
0 Comments