VB.net在连接数据库之前检查数据库是否存在

时间:2016-04-24 23:13:46

标签: sql sql-server database vb.net sql-server-2012

found以下查询,以确定是否已创建数据库表:

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()

当然,问题在于我必须首先知道数据库名称才能连接到数据库。

然后,我似乎可以使用以下方法连接到数据库:

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 As String = cmd.ExecuteNonQuery()上引发错误:

  

附加信息:')'附近的语法不正确。

所以为了纠正查询问题,我不能确定我缺少什么?

需要知道如何让查询回来并说'存在'或'不'

2 个答案:

答案 0 :(得分:2)

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返回所选第一行的第一列。上面的查询只返回一行有一个值,以便它返回什么。

答案 1 :(得分:0)

或者像这样做

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

如果它返回一行,那么数据库就存在,如果不存在则不存在。

要检查数据库中是否存在表,请使用此

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