【问题标题】:how to check if a database exist?如何检查数据库是否存在?
【发布时间】:2013-09-03 03:52:47
【问题描述】:

我正在尝试使用 delphi 7 连接到 sql server 2008 中的数据库。我有一个包含数据库名称的数组 arr_foo。这是我的脚本的样子:

for i:=3 to 5 do begin
  sql := 'SELECT * FROM sys.databases WHERE name = '+quotedstr(arr_foo[i]);
  adoquery1.close;
  adoquery1.sql.text := sql;
  adoquery1.open;
  if not adoquery1.isempty then begin
    adoconnection1.close;
    adoconnection1.defaultdatabase := arr_foo[i];
    adoconnection1.open;
  end;
end;

首先,adoquery1 已经连接到 adoconnection1。 adoconnection1 连接到 //192.168.5.211(这是我的服务器)。

问题是当我在 delphi 7 上运行上述脚本时,它返回错误“属性值无效。请确保输入的值正确”并在“adoquery1.open”处停止,但是当我在 SQL SERVER Management Studio 2008 中运行查询 SELECT * FROM sys.databases WHERE name = 'mydb3' 时,它通常会返回 1 条记录。我的脚本有什么问题?

【问题讨论】:

  • 在 SQL Server 中,当您使用 Management Studio 登录服务器时,您会自动连接到“主”数据库,这就是查询有效的原因。我不认为 adoconnection 这样做。

标签: sql-server sql-server-2008 delphi database-connection delphi-7


【解决方案1】:

尝试使用DB_ID函数-

IF DB_ID('AdventureWorks2008R2') IS NOT NULL
    PRINT 'exists'

对此更改查询:

sql := 'SELECT ID = DB_ID(' + quotedstr(arr_foo[i]) + ')';

并检查 ID 值是否不为空。

【讨论】:

  • 谢谢。这解决了它。由于没有其他人回答,我将其标记为正确答案。
猜你喜欢
  • 2010-10-24
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多