千家信息网

VB.NET数据库怎么用

发表于:2025-11-11 作者:千家信息网编辑
千家信息网最后更新 2025年11月11日,这篇文章主要为大家展示了"VB.NET数据库怎么用",内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下"VB.NET数据库怎么用"这篇文章吧。VB.NET数据库代
千家信息网最后更新 2025年11月11日VB.NET数据库怎么用

这篇文章主要为大家展示了"VB.NET数据库怎么用",内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下"VB.NET数据库怎么用"这篇文章吧。

VB.NET数据库代码示例:

  1. Imports System

  2. Imports System.Data

  3. Imports System.Data.SqlClient

  4. public Class MainClassclass MainClass

  5. Shared Sub Main()Sub Main()

  6. Dim thisConnection As New SqlConnection
    ("server=(local)\SQLEXPRESS;" & _

  7. "integrated security=sspi;database=
    MyDatabase")

  8. ' Sql Query

  9. Dim sql As String = "SELECT *
    FROM Employee "

  10. Dim insertSql As String = "INSERT
    INTO Employee "
    & _

  11. "(ID, FirstName, LastName)VALUES" & _

  12. "(@ID, @FirstName, @LastName)"

  13. Try

  14. ' Create Data Adapter

  15. Dim da As New SqlDataAdapter

  16. da.SelectCommand = New SqlCommand
    (sql, thisConnection)

  17. ' Create and fill Dataset

  18. Dim ds As New DataSet

  19. da.Fill(ds, "Employee")

  20. ' Get the Data Table

  21. Dim dt As DataTable = ds.Tables
    ("Employee")

  22. ' Display Rows Before Changed

  23. Console.WriteLine("Before altering
    the dataset")

  24. For Each row As DataRow In dt.Rows

  25. Console.WriteLine("{0} | {1} | {2}", _

  26. row("ID").ToString().PadRight(10), _

  27. row("FirstName").ToString().PadRight(10), _

  28. row("LastName"))

  29. Next

  30. ' Add A Row

  31. Dim newRow As DataRow = dt.NewRow()

  32. newRow("FirstName") = "Edna"

  33. newRow("LastName") = "Everage"

  34. newRow("ID") = "2"

  35. dt.Rows.Add(newRow)

  36. ' Display Rows After Alteration

  37. Console.WriteLine("=========")

  38. Console.WriteLine("After
    altering the dataset")

  39. For Each row As DataRow In dt.Rows

  40. Console.WriteLine("{0} | {1} | {2}", _

  41. row("ID").ToString().PadRight(10), _

  42. row("FirstName").ToString().PadRight(10), _

  43. row("LastName"))

  44. Next

  45. ' Insert employees

  46. ' 1. Create command

  47. Dim insertCmd As New SqlCommand
    (insertSql, thisConnection)

  48. ' 2. Map parameters

  49. insertCmd.Parameters.Add("@FirstName", _

  50. SqlDbType.NVarChar, 10, "FirstName")

  51. insertCmd.Parameters.Add("@LastName", _

  52. SqlDbType.NVarChar, 20, "LastName")

  53. insertCmd.Parameters.Add("@ID", _

  54. SqlDbType.Int, 15, "ID")

  55. ' 3. Insert employees

  56. da.InsertCommand = insertCmd

  57. da.Update(ds, "Employee")

  58. Catch ex As SqlException

  59. ' Display error

  60. Console.WriteLine("Error: "
    & ex.ToString())

  61. Finally

  62. ' Close Connection

  63. thisConnection.Close()

  64. Console.WriteLine("Connection
    Closed")

  65. End Try

  66. End Sub

  67. End Class

以上是"VB.NET数据库怎么用"这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

0