Example to create a table with all datatypes in MySQL using JDBC?


Java provides supporting classes/datatypes to store all the MySQL datatypes, following is the table which list outs the respective java types for MySQL datatypes −

MySQL TypeJava Type
CHARString
VARCHARString
LONGVARCHARString
NUMERICjava.math.BigDecimal
DECIMALjava.math.BigDecimal
BITboolean
TINYINTbyte
SMALLINTshort
INTEGERint
BIGINTlong
REALfloat
FLOATdouble
DOUBLEdouble
BINARYbyte []
VARBINARYbyte []
LONGVARBINARYbyte []
DATEjava.sql.Date
TIMEjava.sql.Time
TIMESTAMPjava.sql.Tiimestamp

Example

Following JDBC program creates a table with name sample with all the possible datatypes in MySQL −

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class CreatingTable_AllDatatypes {
   public static void main(String args[])throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampledatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Query to create a table with all the supported data types
      String query = "CREATE table sample_table ("
         + "varchar_column VARCHAR( 20 ), "
         + "tinyint_column TINYINT, "
         + "text_column TEXT, "
         + "date_column DATE, "
         + "smallint_column SMALLINT, "
         + "mediumint_column MEDIUMINT, "
         + "int_column INT, "
         + "bigint_column BIGINT, "
         + "float_column FLOAT( 10, 2 ), "
         + "double_column DOUBLE, "
         + "decimal_column DECIMAL( 10, 2 ), "
         + "datetime_column DATETIME, "
         + "timestamp_column TIMESTAMP, "
         + "time_column TIME, "
         + "year_column YEAR, "
         + "char_column CHAR( 10 ), "
         + "tinyblob_column TINYBLOB, "
         + "tinytext_column TINYTEXT, "
         + "blob_column BLOB, "
         + "mediumblob_column MEDIUMBLOB, "
         + "mediumtext_column MEDIUMTEXT, "
         + "longblob_column LONGBLOB, "
         + "longtext_column LONGTEXT, "
         + "enum_column ENUM( '1', '2', '3' ), "
         + "set_column SET( '1', '2', '3' ), "
         + "bool_column BOOL, "
         + "binary_column BINARY( 20 ), "
         + "varbinary_column VARBINARY( 20 )"
      + ")";
      //Executing the query
      stmt.execute(query);
      System.out.println("Table created ........");
   }
}

Output

Connection established......
Table created ........

Updated on: 29-Jun-2020

804 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements