Home » Java programming language

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.
Submitted by Manu Jemini, on October 12, 2017

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.

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

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.

Consider the program:

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

public class CreateTable {
	public static void main(String[] args) {
			//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

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.