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

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


首先要拿到数据库连接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)){ //hsqlMysqL
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;
}

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...