Java提供了支持的类/数据类型来存储所有MySQL数据类型,下表是列出了MySQL数据类型的相应Java类型的表-
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 |
以下JDBC程序创建一个表,该表的名称示例为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 { //注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //获得连接 String mysqlUrl = "jdbc:mysql://localhost/sampledatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //创建一个Statement对象 Statement stmt = con.createStatement(); //查询以创建具有所有支持的数据类型的表 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 )" + ")"; //执行查询 stmt.execute(query); System.out.println("Table created ........"); } }
输出结果
Connection established...... Table created ........