SQL Server 判断数据库表是否存在以及修改表名
2022-11-12 09:45:20
内容摘要
这篇文章主要为大家详细介绍了SQL Server 判断数据库表是否存在以及修改表名,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记!一、判断数据
文章正文
这篇文章主要为大家详细介绍了SQL Server 判断数据库表是否存在以及修改表名,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记!
一、判断数据库表是否存在:首先要拿到数据库连接conn,调用DatabaseMetaData dbmd = conn.getDataMeta();之后调用如下方法:代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <code> /** * 根据表名,判断数据库表是否存在 * @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; } </code> |
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <code> /** * 修改表名 * @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; } </code> |
注:关于SQL Server 判断数据库表是否存在以及修改表名的内容就先介绍到这里,更多相关文章的可以留意
代码注释