簡體   English   中英

VB.net在連接數據庫之前檢查數據庫是否存在

[英]VB.net Checking if database exists before connecting to it

發現以下查詢,以了解是否已創建數據庫表:

if db_id('thedbName') is not null
   --code mine :)
   print 'db exists'
else
   print 'nope'

現在,我想在我的VB.net應用程序中使用相同的查詢。 這是我當前在其他地方可以連接到數據庫的代碼(在執行所有操作之前,我想查看它是否在其中):

Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
                                            "Initial Catalog=thedbName;" & _
                                            "Integrated Security=True;" & _
                                            "Pooling=False")

    Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
                            "Print() 'exists' " & vbCrLf & _
                        "else " & vbCrLf & _
                            "Print() 'nope'"

    Dim cmd As SqlCommand = New SqlCommand(sql, cn)

    cmd.Connection.Open()
    Dim blah As String = cmd.ExecuteNonQuery()
    cmd.Connection.Close()

當然,與此相關的問題是,我必須首先知道數據庫名稱才能連接到數據庫。

然后,我似乎可以使用以下方法連接到master數據庫:

Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
                                            "Integrated Security=True;" & _
                                            "Pooling=False")

    Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
                            "Print() 'exists' " & vbCrLf & _
                        "else " & vbCrLf & _
                            "Print() 'nope'"

    Dim cmd As SqlCommand = New SqlCommand(sql, cn)

    cmd.Connection.Open()
    Dim blah As String = cmd.ExecuteNonQuery()
    cmd.Connection.Close()

但是該查詢似乎在Dim blah上引發錯誤, 因為String = cmd.ExecuteNonQuery()的以下內容:

附加信息:')'附近的語法不正確。

因此,我不確定是否要糾正查詢中的問題嗎?

需要知道如何讓查詢返回並說“存在”或“不”

Print()更改為Print (刪除括號。)


更好的是,根本不使用“ Print ,而使用select

Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
                        "select 'exists' " & vbCrLf & _
                    "else " & vbCrLf & _
                        "select 'nope'"

Dim blah As String = CType(cmd.ExecuteScalar(), string)

ExecuteNonQuery返回受影響的行數以進行更新和插入。 但是您正在執行的查詢。

ExecuteScalar返回所選第一行的第一列。 上面的查詢僅返回具有一個值的一行,因此它將返回。

或這樣做

select * from sys.databases where [name] = 'thedbName'

如果返回一行,則表明數據庫存在,如果不存在,則不存在。

要檢查數據庫中是否存在表,請使用此命令

select * from sys.objects where [name] = 'theTableName' and type_desc = 'USER_TABLE'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM