How to create a table using JDBC in Java?

In this article, we are going to how to create table in MySQL database using JDBC through Java program? It's an example of MySQL database connection using JDBC with creating a table. By Manu Jemini Last updated : March 23, 2024

Create a table using JDBC

To connect and create a table in the MySQL database through java program by using JDBC, we need to install MySQL Sever.

In Java program, to establish connection with the database, we need hostname (Server name, in case of same system we use localhost) with database name, port no, database username and database password.

Database details

Here in this example, we are using following details to connect to the database:

  • Hostname: localhost
  • Database name: demo
  • Port number: 3306
  • Username: root
  • Password: 123

Steps to create a table using JDBC

  • Now, we need to create an object of Connection class and connect to the database by using above given details using DriverManager.getConnection() method.
  • Then, we need to create an object of Statement class to prepare MySQL query to be executed. To create an object of Statement class we use: Statement smt=cn.createStatement();
  • Here, Statement is class name, smt is the object name, cn is the object of Connection class and createStatement() is the method which initialize the object of statement class.
  • After, preparing a query we need to execute it by using executeUpdate() method, which is a method of Statement class.

Java program to create a table using JDBC in Java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class CreateTable {
  public static void main(String[] args) {
    try {

      // serverhost = localhost, port=3306, username=root, password=123
      Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "123");
      Statement smt = cn.createStatement();

      // query to create table Employees with 
      // fields name(empid,empname,dob,city,salary)
      String q = "create table Employees(empid varchar(10) primary key,empname varchar(45),dob date,city varchar(45),salary varchar(45))";

      // to execute the update
      System.out.println("Table Created....");


    } catch (Exception e) {

Output (In console)

Table Created...

Output (In Database)

Create table using JDBC in Java

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.