2014-07-26 33 views
4

使用VB.NET,我成功創建了一個新數據庫,並將數據從Excel文件導入到一個表中,並導入到SQL Server 2012 Express數據庫中。新表使用默認架構dbo創建。SQL Server數據庫使用VB.NET的新模式

我想爲剛剛創建的數據庫(即cad)創建一個新模式並將該表分配給此新模式。我很難用VB.NET來做這件事。以下是創建與Excel文件具有相同名稱的數據庫的代碼。接下來是將cad模式添加到此數據庫。一旦創建完成,我可以導入Excel數據並將新模式包含在連接字符串中。

SQL_Server = Me.TxtServer.Text       'assing variable for the SQL server 
SQL_DBNam = Me.TxtDbName.Text       'assign variable for the database name in the server 
SQL_Table = Me.TxtInsertedTableName.Text    'assign variable for the table name in the database in the server 
SQL_Schema = Me.TxtSchema.Text 
'save the schema to registry in case it had been altered 
SaveSetting("CAD SQUAD", SD_LogNam, "SQLSchema", SQL_Schema) 

''connect to excel file...............xls................xls................xls....................xls.......... 

''32bit excel 
'Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.jet.OLEDB.4.0;Data Source=" & fullName & ";Extended Properties=Excel 8.0;") 

''64bit excel 
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fullName & ";Extended Properties=Excel 8.0;") 

Try 'try 1 ------------------------------connection to excel file----------------------------------------------- 
    ExcelConnection.Open() 

    ''MsgBox("Excel connection open for file " & fullName) 

    ''assign string to select all items from excel sheet 
    Dim expr As String = "SELECT * FROM [" & XLS_Sheet & "]" 

    ''MsgBox("String to connect to EXCEL table = " & expr) 

    Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection) 
    Dim objDR As OleDbDataReader 
    Dim DBExists As Byte = 0 

    ''connect to SQL server (leave 'Database' parameter blank as it does not yet exist) 
    ''check which type of connection 
    IE_SrvStr = ServerConnString(CheckBox_TrustCon.Checked, "") 

    'MsgBox("Server connect string: " & IE_SrvStr) 

    IE_SrvConn = New SqlConnection(IE_SrvStr) 


    Try 'try 2 
     'open server connection 
     IE_SrvConn.Open() 

     'check if database exists (moved from above)========================================================== 
     Dim DBObj As SqlCommand 
     Dim DBStr As String 

     Dim DB_Cmd As SqlCommand = New SqlCommand("SELECT case when exists (select 1 from sys.Databases where Name = @DbName) then 1 else 0 end as DbExists", IE_SrvConn) 
     DB_Cmd.Parameters.AddWithValue("@DbName", SQL_DBNam) 
     '================================================== 

     DBExists = CByte(DB_Cmd.ExecuteScalar()) 

     If DBExists = 1 Then 

      ListBoxEvent.Items.Add("Database " & SQL_DBNam & " already exists...") 
      ListBoxEvent.SelectedIndex = ListBoxEvent.Items.Count - 1 
      'MsgBox("Database " & SQL_DBNam & " already exists... OK to continue") 
     Else 
      ''create database 
      DBObj = IE_SrvConn.CreateCommand() 
      DBStr = "CREATE DATABASE " & SQL_DBNam 

      ListBoxEvent.Items.Add("Database " & SQL_DBNam & " created successfuly...") 
      ListBoxEvent.SelectedIndex = ListBoxEvent.Items.Count - 1 
      'MsgBox(SQL_DBNam & " Database Created... OK to continue!") 

      ''execute 
      DBObj.CommandText = DBStr 
      DBObj.ExecuteNonQuery() 

     End If 

     IE_SrvConn.Close() 
      Try 'try 3 


       'and open server 
       IE_SrvConn.Open() 

       ''check if table exists+++++++++++++++++++++++++++++++++++++++++++++++++++++ 

       Dim restrictions(3) As String 
       restrictions(2) = SQL_Table 
       Dim dbTbl As DataTable = IE_SrvConn.GetSchema("Tables", restrictions) 

       If dbTbl.Rows.Count = 0 Then 
        'Table does not exist 
        'DoesTheTableExist = False 

        Dim TBObj As New SqlCommand 
        Dim TBStr As String 

        TBObj = IE_SrvConn.CreateCommand() 
        ''the .cad schema is what I want to assing to the table but 
        ''it errors out: shcema not available or you do not have permissions 
        ''when using the .dbo it works fine 
        'TBStr = "CREATE TABLE " & SQL_DBNam & ".cad" & ". " & SQL_Table & "(" & _ 

         TBStr = "CREATE TABLE " & SQL_DBNam & ".dbo" & ". " & SQL_Table & "(" & _ 
         "LayIdx int NOT NULL PRIMARY KEY, " & _ 
         "New_LayNam VARCHAR(255), " & _ 
         . 
         . 
         . 

         "LayDescription VARCHAR(255)" & _ 
         ") " 

        'MsgBox("Table parameters: " & TBStr) 
        ' Execute 
        TBObj.CommandText = TBStr 
        'MsgBox("TBOBJ.CommandText = initiated command!") 
        TBObj.ExecuteNonQuery() 
        'MsgBox("TBOBJ.ExecuteNonQuery()-executed! now see if table is available...") 
       Else 
        ''table exists; (option: ask if want to delete it and replace with new....) 
        ListBoxEvent.Items.Add("Table " & SQL_Table & " already exists...") 
        ListBoxEvent.SelectedIndex = ListBoxEvent.Items.Count - 1 
        'MsgBox("Table " & SQL_Table & " exists...OK to Continue!") 
       End If 

       dbTbl.Dispose() 

       ''check if record exists, means table has already been populated 

       'MsgBox("Find records on the table...") 

       Dim tblRecs As String = "SELECT * FROM " & SQL_Table 
       Dim tblCmd As SqlCommand = New SqlCommand(tblRecs, IE_SrvConn) 

       Using RReader As SqlDataReader = tblCmd.ExecuteReader() 
        If RReader.HasRows Then 
         RReader.Close() 
         ListBoxEvent.Items.Add("Table data is already imported...") 
         ListBoxEvent.SelectedIndex = ListBoxEvent.Items.Count - 1 
         'MsgBox("Table is already populated...OK to Finish!") 
        Else 
         ''propulate table 
         RReader.Close() 
         'MsgBox("SQL_Table exists but has not records... OK to Import Data!") 

         'importing from excel 
         Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(IE_SrvConn) 

          bulkCopy.DestinationTableName = SQL_Table 

          Try 'try 4 
           objDR = objCmdSelect.ExecuteReader 
           bulkCopy.WriteToServer(objDR) 

           ExcelConnection.Close() 
           IE_SrvConn.Close() 
           ListBoxEvent.Items.Add("Data import successful!") 
           ListBoxEvent.SelectedIndex = ListBoxEvent.Items.Count - 1 
          Catch ex As Exception 
           MsgBox("Error importing to table " & SQL_Table & ": " & ex.ToString) 
          End Try 'try 4 close 

         End Using 

        End If 

       End Using 


      Catch ex As Exception 
       MsgBox("Error creating table: " & SQL_Table & " in database: " & SQL_DBNam & " [" & ex.Message & "]") 
       Exit Sub 
      Finally 
       IE_SrvConn.Close() 'Whether there is error or not. Close the connection. 
       ExcelConnection.Close() 
       ListBoxEvent.Items.Add("Closing connection to server " & SQL_Server) 
       ListBoxEvent.SelectedIndex = ListBoxEvent.Items.Count - 1 
       'MsgBox("Connection to Server " & SQL_Server & " closed!") 
      End Try 'try 3 close 
+0

我沒有看到在上面的代碼,在那裏得到創建表的任何地方,你能不能請檢查您是否已經張貼整個代碼,否則你可以指向行號表是被創建。 – Surendra

+0

是的,這裏是表格創建代碼: – CadSquad

回答

0

在這裏你去下面的代碼片段顯示您正在使用dbo架構創建

TBStr = "CREATE TABLE " & SQL_DBNam & ".dbo" & ". " & SQL_Table & "(" & _ 
         "LayIdx int NOT NULL PRIMARY KEY, " & _ 
         "New_LayNam VARCHAR(255), " & _ 
         . 
         . 
         . 

         "LayDescription VARCHAR(255)" & _ 
         ") " 

,而是如果你想讓它與CAD方案中創建,那麼你必須使用語句如下

TBStr = "CREATE TABLE " & SQL_DBNam & ".cad" & ". " & SQL_Table & "(" & _ 
         "LayIdx int NOT NULL PRIMARY KEY, " & _ 
         "New_LayNam VARCHAR(255), " & _ 
         . 
         . 
         . 

         "LayDescription VARCHAR(255)" & _ 
         ") " 

remember, once the table is created with a schema other than the default schema of the database (usually dbo), then you have to specify the schema name while doing any operations such as select, update, delete, insert on the table.

+0

感謝您的回覆,我在創建表格時調用了.cad模式。該模塊創建一個數據庫,然後創建該數據庫下的一個表,因此cad模式不會作爲新創建數據庫的安全性的一部分存在,因此當我使用.cad模式創建表時,我收到一個錯誤:[The指定的模式名稱「cad」或者不存在,或者您沒有使用它的權限]。在創建數據庫之後並在創建表之前,似乎需要創建cad模式。這是我遇到的麻煩。 – CadSquad

+0

有人認爲這可能會工作是使用VB.NET在SQL中創建一個腳本來添加.cad模式,然後在代碼創建數據庫後運行腳本。接下來使用.cad創建表應該能夠像數據庫中已經存在的模式那樣工作。如何去做這件事? – CadSquad

0

這裏是我找到成功地創建一個SQL Server EXPRES一個新的模式的代碼的數據庫

Imports Microsoft.SqlServer.Management.Smo 
Imports Microsoft.SqlServer.Management.Common 
Imports System.Data.SqlClient 

Module DBSchema 
    Public Sub TableSchema(SrvName As String, DBaseName As String, SchName As String, SchOwner As String) 
     Dim connectionString As String = "Data Source=" & SrvName & ";Initial Catalog=" & DBaseName & ";Integrated Security=SSPI;" 
     Dim connection As New SqlConnection(connectionString) 
     ' do not explicitly open connection, it will be opened when Server is initialized 
     connection.Open() 
     Dim serverConnection As New ServerConnection(connection) 
     Dim server As New Server(serverConnection) 
     Console.Write("server connection defined...") 
     ' after this line, the default database will be switched to Master 
     Dim database As Database = server.Databases(DBaseName) 
     ' if you want to execute a script against this database, you have to open 
     ' another connection and re-initiliaze the server object 
     server.ConnectionContext.Disconnect() 
     connection = New SqlConnection(connectionString) 
     serverConnection = New ServerConnection(connection) 
     server = New Server(serverConnection) 
     'Create the schema on the instance of SQL Server. 
     Dim sch As Schema 
     sch = New Schema(database, SchName) 
     sch.Owner = SchName 
     sch.Create() 
     connection.Close() 
    End Sub 
End Module 
相關問題