使用 JDBC 在 MySQL 中创建包含所有数据类型的表的示例?
jdbcobject oriented programmingprogramming
Java 提供支持类/数据类型来存储所有 MySQL 数据类型,下表列出了 MySQL 数据类型的相应 Java 类型 −
MySQL 类型 | Java类型 |
---|---|
CHAR | 字符串 |
VARCHAR | 字符串 |
LONGVARCHAR | 字符串 |
NUMERIC | java.math.BigDecimal |
DECIMAL | java.math.BigDecimal |
BIT | 布尔值 |
TINYINT | 字节 |
SMALLINT | 短整型 |
INTEGER | 整数 |
BIGINT | 长整型 |
REAL | 浮点型 |
FLOAT | 双精度型 |
DOUBLE | 双精度型 |
二进制 | 字节[] |
VARBINARY | byte [] |
LONGVARBINARY | byte [] |
DATE | java.sql.Date |
TIME | java.sql.Time |
TIMESTAMP | java.sql.Tiimestamp |
示例
以下 JDBC 程序创建一个名为 sample 的表,其中包含 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("连接已建立......"); //创建 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 ........