判断数据库是否存在:
// 判断数据库是否存在
String sql = "select * From master.dbo.sysdatabases where name='数据库'";
// get connection
Connection conn = SqlUtils.getConnection();
Statement statement = null;
ResultSet resultSet = null;
try {
// get statement
statement = conn.createStatement();
// run sql
resultSet = statement.executeQuery(sql);
// 如果结果集有值则有库 否则无库-进行创建数据库操作
if (!resultSet.next()) {
System.out.println("数据库不存在");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close Resource
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e1) {
e1.printStackTrace();
} finally {
try {
if (statement != null)
statement.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
判断数据库中指定表是否存在:
Connection conn = null;
Statement statement = null;
try {
conn = SqlUtils.getConnection();
statement = conn.createStatement();
statement.execute("use 数据库");
// 获取日期
Date date = new Date();
SimpleDateFormat simple = new SimpleDateFormat("yyyy_MM_dd");
todayTableName = "Q" + simple.format(date);
// 判断表是否存在 不存在则创建表
String sql = "SELECT name FROM sysobjects WHERE name = N'表名' AND type = 'U'";
ResultSet rs = statement.executeQuery(sql);
if (!rs.next()) {
System.out.println("数据表不存在");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close Resource
try {
if (statement != null)
statement.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
如有疑问请在下发评论
关注我,获取更多~