Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Type | Java Type |
|---|---|
| CHAR | String |
| VARCHAR | String |
| LONGVARCHAR | String |
| NUMERIC | java.math.BigDecimal |
| DECIMAL | java.math.BigDecimal |
| BIT | boolean |
| TINYINT | byte |
| SMALLINT | short |
| INTEGER | int |
| BIGINT | long |
| REAL | float |
| FLOAT | double |
| DOUBLE | double |
| BINARY | byte [] |
| VARBINARY | byte [] |
| LONGVARBINARY | byte [] |
| DATE | java.sql.Date |
| TIME | java.sql.Time |
| TIMESTAMP | java.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 ........
Advertisements