mysql 修改表名 判断表是否存在_判断数据库表是否存在以及修改表名的方法

一、判断数据库表是否存在:

首先要拿到数据库连接conn,调用DatabaseMetaData dbmd = conn.getDataMeta();之后调用如下方法:

复制代码 代码如下:

/**

* 根据表名,判断数据库表是否存在

* @param tableName

* @return true:存在该表,false:不存在该表

*/

public boolean hasTable(String tableName) {

Init();

boolean result = false; //判断某一个表是否存在

try{

ResultSet set = dbmd.getTables (null, null, tableName, null); //获取查找结果

while (set.next()) { //如果查找结果不为空,则说明存在该表

result = true; //将返回结果置为true

}

}catch(Exception e){

e.printStackTrace();

}

return result;

}

二、修改表名:

首先依然要拿到数据库连接conn和数据库描述对象dbmd以及Statement对象st,之后调用如下方法

复制代码 代码如下:

/**

* 修改表名

* @param srcTableName 源表名

* @param newTableName 新表名

* @return true:修改表名成功,false:修改表名失败

*/

public boolean renameTable(String srcTableName,String newTableName){

Init();

boolean result = false;

StringBuffer sql = new StringBuffer();

try{

String dataBaseType = dbmd.getDatabaseProductName(); //获取数据库类型

if(("Microsoft SQL Server").equals(dataBaseType)){ //sqlServer

try{

sql.append("EXEC sp_rename"+" "+srcTableName).append(",").append(newTableName);

int temp = 0;

temp = st.executeUpdate(sql.toString()); //执行更新操作,返回结果

if(1==temp){

result = true; //将返回值设为true

}

}catch(Exception e){

e.printStackTrace();

}

}else if(("HSQL Database Engine").equals(dataBaseType)||("MySQL").equals(dataBaseType)){ //hsql和mysql

try{

sql.append("ALTER TABLE"+" "+srcTableName+" "+"RENAME TO"+" "+newTableName);

int temp = 1;

temp = st.executeUpdate(sql.toString()); //执行更新操作,返回结果

if(0==temp){

result = true; //将返回值设为true

}

}catch(Exception e){

e.printStackTrace();

}

}else{ //尚未实现对oracle和db2判断

}

}catch(Exception e){

e.printStackTrace();

}

//System.out.println(result);

return result;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值