java 创建MySQL表

我知道语句。如
create table UserInfo(
id int parmary key,
name varchar(20) not null,
age int not null
)
能解释一下具体参数的意义么

create table UserInfo( 创建 表 表名 这里create table是固定写法,表名自己起
id int parmary key, 列名,数据类型。parmary key表示该列为主键列
name varchar(20) not null, 列名,数据类型(数据长度)。not null表示该列不允许为空
age int not null 这个同上
)追问

长度可以设为动态的么

追答

对于name这种字符串,可以设置为varchar,这就是动态的了。

追问

那个20不是表中的行数么?还是字符串中字符的个数?

追答

20是这个字段的长度,也就是最大能存储多少。
但是实际上即便设置了20,也能存储超过20个字符。这个你可以试试。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-06-30
Java 使用executeUpdate向数据库中创建表格

一、创建mysql.ini文件,配置如下

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/select_test
user=root
pass=123456

这样以后修改数据库的配置直接在mysql.ini文件中修改。

二、编写代码

 initParam方法: 获得mysql.ini中的数据

createTale方法: 连接数据库,并且executeUpdate执行sql语句。此例的sql文件为创建表语句。

 main方法: 传入Sql语句。

class ExecuteDDL {

private String driver;
private String url;
private String user;
private String pass;
Connection conn;
Statement stmt;
public void initParam(String paramFile) throws Exception {
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pass = props.getProperty("pass");
}

public void createTale(String sql) throws Exception{
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,pass);
stmt = conn.createStatement();
stmt.executeUpdate(sql);
}
finally
{
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
}

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub

ExecuteDDL ed = new ExecuteDDL();
ed.initParam("src/mysql.ini");
ed.createTale("create table student " +
"(id int, " +
"name varchar(50), " +
"num varchar(20) )");
System.out.println("Creating table success!");
}

 注意事项:传入的Sql语句最好在MySql测试通过,并且传入的mysql.int文件的路径必须正确。 

当执行完毕后,在MySql的select_test数据库中查看该Student表是否已经创建成功了。

三、使用executeUpdate方法,向表中插入数据。

将上面的创建表的Sql语句改为插入数据表的语句,执行executeUpdate方法,其结果就是想表中插入数据。

创建insertSql变量。

private static String insertSql = "insert into student values(1,'XiaoMing','06108787')";

 执行插入语句。

ed.createTale(insertSql);
第2个回答  2012-05-22
创建一个表UserInfo
有三个字段:id,name和age
id是主键 primary key
name 是字符串型的,长度为20,不为空
age 为int型的,不为空
create table UserInfo(
id int primary key,
name varchar(20) not null,
age int not null
);追问

长度可以设为动态的么

第3个回答  2012-05-22
20表示能存储10个字符10个汉字
相似回答