欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-12 14:58:58
一、判断数据库表是否存在: 首先要拿到数据库连接conn,调用databasemetadata dbmd = conn.getdatameta();之后调用如下方法: 复制...
一、判断数据库表是否存在:
首先要拿到数据库连接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;
}