2016-04-24 52 views
0

found下面的查询,以找出是否一个数据库表已经或没有创建:VB.net检查是否数据库连接之前,存在

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

但该查询似乎扔在点心等等的String = cmd.ExecuteNonQuery()的错误:

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

因此,我不是所有人都确定我错过了什么以纠正查询问题?

需要知道如何让查询回来说“存在”或“没了”

+0

你首先包括在你的代码之前运行数据库的查询? – jamiedanq

+1

[如何检查一个数据库和表是否存在于一个vb.net项目的sql服务器?](http://stackoverflow.com/questions/25162815/how-to-check-if-a-database- sql-server-in-a-vb-net-project) – MrGadget

+0

是的,使用SQL管理工作室的查询工作得很好。 – StealthRT

回答

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返回所选第一行的第一列。上面的查询只返回一行一个值,这就是它会返回的内容。

+0

感谢您的发现。没有错误,但它不断返回** - 1 **而不是'存在'或'不'' – StealthRT

+0

**伟大的斯科特!**哈。感谢您的示例代码。它现在工作得很好! – StealthRT

0

或做这样的

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

如果返回行,那么数据库存在,如果不是那么它没有。

要检查表的数据库中存在,使用这种

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