2010-02-09 8 views
29

이것은 매우 사소한 것처럼 보이지만 지금은 절망적입니다.만들기 전에 데이터베이스가 있는지 확인하십시오.

SQL Server 2005 Express에서 C#을 사용하고 있습니다.

다음 코드를 사용하고 있습니다. 데이터베이스를 만들기 전에 데이터베이스가 있는지 확인하고 싶습니다. 그러나 반환 된 정수는 -1이며 ExecuteNonQuery()가 반환 할 내용을 MSDN에서 정의하는 방식입니다. 지금 당장 데이터베이스는 존재하지만 여전히 -1을 반환합니다. 그런 말로, 원하는 결과를 얻기 위해 어떻게이 일을 할 수 있습니까?

private static void checkInventoryDatabaseExists(ref SqlConnection tmpConn, ref bool databaseExists) 
{ 
    string sqlCreateDBQuery; 
    try 
    { 
     tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes"); 

     sqlCreateDBQuery = "SELECT * FROM master.dbo.sysdatabases where name = 
     \'INVENTORY\'"; 

     using (tmpConn) 
     { 
      tmpConn.Open(); 
      tmpConn.ChangeDatabase("master"); 

      using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn)) 
      { 
       int exists = sqlCmd.ExecuteNonQuery(); 

       if (exists <= 0) 
        databaseExists = false; 
       else 
        databaseExists = true; 
      } 
     } 
    } 
    catch (Exception ex) { } 

} 

답변

43

은 이전 스타일의 sysobjectssysdatabases 그 카탈로그 뷰는 SELECT @DatabaseID = DB_ID('INVENTORY')를 사용되지 않습니다 :

당신은 처리 결과 집합의 예 SELECT DB_ID('INVENTORY') AS DatabaseID 사용하거나 변수/매개 변수를 사용해야합니다. 사용 sys. 스키마를 - - 대신이 작업을 수행 sys.databases

private static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName) 
{ 
    string sqlCreateDBQuery; 
    bool result = false; 

    try 
    { 
     tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes"); 

     sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name 
     = '{0}'", databaseName); 

     using (tmpConn) 
     { 
      using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn)) 
      { 
       tmpConn.Open(); 

       object resultObj = sqlCmd.ExecuteScalar(); 

       int databaseID = 0;  

       if (resultObj != null) 
       { 
        int.TryParse(resultObj.ToString(), out databaseID); 
       } 

       tmpConn.Close(); 

       result = (databaseID > 0); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     result = false; 
    } 

    return result; 
} 

이이 같은 전망은 매개 변수로 전달할 데이터베이스 이름으로 작동, 그것은 부울 진정한 = 데이터베이스가 거짓 = 데이터베이스가 존재하지 않는 존재 돌아갑니다 (또는 오류가 발생했습니다).

+1

시도해보십시오 .. 실행 전에 executeCalar가 객체를 반환하므로 할당 전에 캐스팅해야합니다. –

+0

"잘못된 열 이름 'INVENTORY'"INVENTORY ' " –

+1

예외가 throw됩니다. 죄송합니다, 예 - 데이터베이스 이름을 작은 따옴표로 - –

6

"SELECT * FROM master.dbo.sysdatabases where name = \'INVENTORY\'" 

이이어야한다? MSDN

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

에 따르면 또한

"SELECT * FROM master.dbo.sysdatabases where name = 'INVENTORY'" 

당신은 아닌 DML 문는 SELECT를하고 있습니다. 대신에 ExecuteReader 메서드를 사용하지 않는 이유는 무엇입니까?

+0

결과에 영향 .. 여전히 -1을 반환 –

+0

나는 당신이 일을하지 않는 대신 이후가 ExecuteReader를 사용합니다 DML 어쨌든 – SQLMenace

+0

이해야 코멘트가 되십시오. 좋은 점 –

2

ExecuteNonQuery을 사용할 수 없습니다. MSDN 링크에서 보여 지듯이 항상 SELECT에 대해 -1을 반환하기 때문입니다. SQL 서버 2005로

2

시스템 뷰를 쿼리하는 대신 데이터베이스의 ID를 반환하는 db_id 함수를 사용할 수 있습니다. 그렇지 않으면 null입니다. 예 T-SQL은 아래 :

if (db_id('INVENTORY') is null) 
begin 
    return 0 
end 
else 
begin 
    return 1 
end 
28

에 몇 년이 읽기 및이를 표현하는 청소기 방법이 : 수색자의 이익을 위해

public static bool CheckDatabaseExists(string connectionString, string databaseName) 
{ 
     using (var connection = new SqlConnection(connectionString)) 
     { 
      using (var command = new SqlCommand($"SELECT db_id('{databaseName}')", connection)) 
      { 
       connection.Open(); 
       return (command.ExecuteScalar() != DBNull.Value); 
      } 
     } 
} 
+0

여기에 SQL 주입을주의하십시오. 문자열 보간 대신 매개 변수화 된 쿼리 사용 – AndrewK

0

당신이 this 것 엔티티 프레임 워크를 사용하는 경우, 작업 :

using (var ctx = new MyDataModel()) 
{ 
    dbExists = System.Data.Entity.Database.Exists(ctx.Database.Connection); 
} 
관련 문제