[转载]如何判断数据库,表或字段是否存在
在添加新的数据库,表或字段的时候,添加之前一般都会检查是否已经存在,这样做的好处是保证脚本的稳定性,再次执行的时候也不会报错了。
有两种方法,一种是使用内置的函数,另外一种是查询系统表,总结的sql脚本如下。
USE master; GO -- 判断数据库是否存在 -- 方法1:使用函数DB_ID IF DB_ID('TestDB') IS NOT NULL DROP DATABASE TestDB; -- 方法2:查询系统表 IF EXISTS(SELECT * FROM sys.sysdatabases WHERE name=N'TestDB') DROP DATABASE TestDB; USE TestDB; GO -- 判断数据表是否存在 -- 方法1:使用函数OBJECT_ID IF OBJECT_ID('dbo.Test','U') IS NOT NULL DROP TABLE dbo.Test; -- 方法2:查询系统表 IF EXISTS(SELECT * FROM sys.syscolumns WHERE OBJECT_ID('dbo.Test')) DROP TABLE dbo.Test; -- 判断字段是否存在 -- 方法1:使用函数COL_LENGTH IF COL_LENGTH('dbo.Test',N'UserId') IS NULL ALTER TABLE dbo.Test ADD Item1 NVARCHAR(max) NULL; -- 方法2:查询系统表 IF EXISTS(SELECT * FROM sys.syscolumns WHERE id=OBJECT_ID('dbo.Test') AND name=N'UserId') PRINT 'UserId已存在' ELSE PRINT 'UserId不存在' -- 刷新视图,因为新增或删除列时可能会影响到视图 IF OBJECT_ID('dbo.ViewOrderIntegral','U') IS NOT NULL EXEC sp_refreshview N'dbo.ViewOrderIntegral';
Mysql
1、判断一个表是否存在
语法:
SELECT table_name FROM information_schema.TABLES WHERE table_name ='表名';
sql例子:
SELECT table_name FROM information_schema.TABLES WHERE table_name ='t_iov_vehicle_owner_info'
存在:
不存在:
备注,sql也可以这样写:
select count(*) from information_schema.tables where table_name='t_iov_vehicle_owner_info'
2、判断表中一个字段是否存在
语法:
select count(*) from information_schema.columns where table_name = '表名' and column_name = '字段名'
sql例子:
select count(*) from information_schema.columns where table_name = 't_iov_vehicle_owner_info' and column_name = 'id'
java可以通过DatabaseMetaData确定数据库中是否存在表和表中是否有列。
参考:
http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html
http://stackoverflow.com/questions/11699205/how-to-check-if-a-table-or-a-column-exists-in-a-database
import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; public class CheckTableAndColumnExist { public static void main(String[] args) { Connection connection = null; try { String userName = "root"; String password = "密码"; String jdbcurl = "jdbc:mysql://localhost:3306/库?useUnicode=true&characterEncoding=utf-8"; Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(jdbcurl, userName, password); DatabaseMetaData md = connection.getMetaData(); String tableName = "表名"; String columnName = "列名"; ResultSet rs = md.getTables(null, null, tableName, null); if (rs.next()) { System.out.println("Table " + tableName + " exist"); rs = md.getColumns(null, null, tableName, columnName); if (rs.next()) { System.out.println("Column " + columnName+ " exist in Table " + tableName); } else { System.out.println("Column " + columnName+ " not exist in Table " + tableName); } } else { System.out.println("Table " + tableName + " not exist"); } } catch (Exception e) { System.err.println("Cannot connect to database server,Exception:" + e.getMessage()); } finally { if (connection != null) { try { connection.close(); connection = null; } catch (Exception e) { /* ignore close errors */ } } } } }