怎样用java代码动态生成数据库表

感谢2楼的回答,我要的是不使用任何框架的 纯jdbc的 根据页面传过来值 动态生成对应的数据库表 并保存数据

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("数据库url","帐号","密码");
state=conn.createStatement();
state.executeUpdate("create 建表语句");
state.executeUpdate("insert 插入数据")------>插入的值由页面获得,注意字符串拼接。
然后就是关闭连接,state.close();conn.close();
核心代码就是这些,具体应用你可以多写几个方法(增删改查),都是类似的,注意异常的处理,关闭连接最好在finally中进行。
温馨提示:内容为网友见解,仅供参考
第1个回答  2011-01-13
这个就要借助hibernate tools跟xdoclet来完成了;
首先你要在你的java代码里应用xdoclet标签,例如
Java code
private String name;

/**
* @hibernate.property column = "name" length = "50"
*/
public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

其中,写到javadoc上的@hibernate.property column = "name" length = "50"
就是xdoclet标签,它需要xdoclet程序来处理,这里就需要用到hibernate tools。
具体做的话一般情况是建一个ant脚本来完成,例如:
XML code
<target name="hibernate-xdoclet" depends="init, init-xdoclet_hibernate"
description="Generate mapping documents">

<echo>+---------------------------------------------------+</echo>
<echo>| |</echo>
<echo>| R U N N I N G H I B E R N A T E D O C L E T |</echo>
<echo>| |</echo>
<echo>+---------------------------------------------------+</echo>

<delete>
<fileset dir="$" includes="hibernate.cfg.xml" />
</delete>
<echo message="hibernate.cfg.xml at $"></echo>
<sleep seconds="1"/>

<hibernatedoclet
destdir="$"
excludedtags="@version,@author,@todo,@see"
addedtags="@xdoclet-generated at $,@copyright The XDoclet Team,@author XDoclet,@version $"
force="false"
verbose="true">

<fileset dir="$">
<include name="com/**/model/**/*.java"/>
</fileset>
<hibernatecfg
version="3.0"
destDir="$"
dialect="org.hibernate.dialect.Oracle9Dialect"
driver="oracle.jdbc.driver.OracleDriver"
jdbcUrl="jdbc:oracle:thin:@localhost:1521:RESDL"
userName="test"
password="123"
showSql="true"
schema="true"
validateXML="true"
/>
<hibernate version="3.0"/>
</hibernatedoclet>

</target>
上面的代码是生成hbm跟cfg文件的,下面再介绍如何从java类到数据库:
XML code
<target name="hibernate-schema" depends="init, init-hibernate-schema"
description="Generate DB schema from the O/R mapping files">

<echo>+---------------------------------------------------+</echo>
<echo>| |</echo>
<echo>| R U N N I N G D B S C H E M A |</echo>
<echo>| |</echo>
<echo>+---------------------------------------------------+</echo>

<echo message="mysql.sql at etc/hbm2doc"></echo>
<sleep seconds="1"/>

<hibernatetool destdir="etc/hbm2doc">
<configuration propertyFile="$/hibernate.properties">
<fileset dir="$">
<include name="com/**/model/**/*.hbm.xml"/>
</fileset>
</configuration>
<hbm2ddl drop="true"
outputfilename="mysql.sql"/>
<hbm2doc/>
</hibernatetool>

</target>

当然ant工程里的一些初始化需要自己定义,我这里只摘录关键部分,具体的东西请查阅相关文档,hibernate tutorail里就有个例子
第2个回答  2011-01-13
1.先与数据库连接,代码自己找 2.然后写一个Sql命令类 专门生成命令和自由搭配 3.将命令传入数据库
第3个回答  2011-01-13
你的 意思是用java语言 建立数据库 数据表么
相似回答