sql - VB.net Checking if database exists before connecting to it -
i found following query in order find out if database table created or not:
if db_id('thedbname') not null --code mine :) print 'db exists' else print 'nope'
now wanting use same query within vb.net application. code have elsewhere connects database (that wanting see if there before doing this):
dim cn sqlconnection = new sqlconnection("data source=davidsdesktop;" & _ "initial catalog=thedbname;" & _ "integrated security=true;" & _ "pooling=false") dim sql string = "if db_id('thedbname') not null " & vbcrlf & _ "print() 'exists' " & vbcrlf & _ "else " & vbcrlf & _ "print() 'nope'" dim cmd sqlcommand = new sqlcommand(sql, cn) cmd.connection.open() dim blah string = cmd.executenonquery() cmd.connection.close()
of course issue have know database name first in order connect database.
i seem able connect master database using this:
dim cn sqlconnection = new sqlconnection("data source=davidsdesktop;" & _ "integrated security=true;" & _ "pooling=false") dim sql string = "if db_id('thedbname') not null " & vbcrlf & _ "print() 'exists' " & vbcrlf & _ "else " & vbcrlf & _ "print() 'nope'" dim cmd sqlcommand = new sqlcommand(sql, cn) cmd.connection.open() dim blah string = cmd.executenonquery() cmd.connection.close()
but query seems throw error on dim blah string = cmd.executenonquery() of:
additional information: incorrect syntax near ')'.
so i'm not sure missing in order correct issue query?
need know how have query come , 'exists' or 'nope'
change print()
print
(remove parentheses.)
better, don't use print
@ all, use select
.
dim sql string = "if db_id('thedbname') not null " & vbcrlf & _ "select 'exists' " & vbcrlf & _ "else " & vbcrlf & _ "select 'nope'" dim blah string = ctype(cmd.executescalar(), string)
executenonquery
returns number of affected rows updates , inserts. executing is query.
executescalar
returns first column of first row selected. query above returns 1 row 1 value, that's return.
Comments
Post a Comment