使用vb.net串連到資料庫並執行命令。

來源:互聯網
上載者:User
資料|資料庫|執行 Imports System
Imports System.Data  '引入資料類庫
Imports System.Data.SqlClient  '引入SQL Server類庫(用來訪問SQL Server)

Module Module1
    Sub Main()
        AddRecord() '增加記錄
        RemoveRecord() '刪除記錄
        Pause()
    End Sub

    Sub Pause()
        Console.WriteLine("Press Enter To Continue...")
        Console.ReadLine()
    End Sub

    Sub AddRecord()
        '定義連接字串
        Dim sConnectionString As String _
            = "User ID=sa;Initial Catalog=pubs;Data Source=(local)"
        '定義一個SQL連線物件  
        Dim objConn As New SqlConnection(sConnectionString)
        '連線物件
        objConn.Open()
        '定義一個插入記錄命令字元
        Dim sSQL As String = "INSERT INTO Employee " & _
          "(emp_id, fname, minit, lname, job_id, job_lvl, pub_id, hire_date)" & _
          "VALUES ('MSD12923F', 'Duncan', 'W', 'Mackenzie', " & _
                   "10, 82,'0877','2001-01-01')"

        Dim objCmd As New SqlCommand(sSQL, objConn)
        Try
            objCmd.ExecuteNonQuery()  '執行插入動作
        Catch e As Exception
            Console.WriteLine(e.Message) '無法執行時提示出錯資訊
        End Try
        Console.WriteLine("Record Added")
    End Sub

    Sub RemoveRecord()
        Dim sConnectionString As String _
            = "User ID=sa;Initial Catalog=pubs;Data Source=(local)"
        Dim objConn As New SqlConnection(sConnectionString)
        objConn.Open()
        Dim sSQL As String = "DELETE FROM Employee WHERE emp_id = @emp_id"
        Dim objCmd As New SqlCommand(sSQL, objConn)

        objCmd.Parameters.Add("@emp_id", SqlDbType.Char, 9)
        objCmd.Parameters.Item("@emp_id").Value = "MSD12923F"

        Try
            objCmd.ExecuteNonQuery()
            Console.WriteLine("Record Deleted")
        Catch e As Exception
            Console.WriteLine(e.ToString)
        End Try
        Console.ReadLine()
    End Sub

End Module


相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。