【问题标题】:Cant save or update my SQL Server tables using vb.net无法使用 vb.net 保存或更新我的 SQL Server 表
【发布时间】:2014-01-14 22:46:18
【问题描述】:

我是 .net 的完全初学者,对一些基本的事情感到困惑。请帮忙。

  1. 首先,我创建和填充的表(通过右键单击服务器资源管理器中的表)在我重新启动计算机后消失。我该如何保留它们。

  2. 有没有比命令提示符更好的地方/界面在 vb.net 中键入 SQL 查询。

在以下代码中:

Dim cn As SqlConnection = New SqlConnection(strConnection)
cn.Open( )
' Create a data adapter object and set its SELECT command.
Dim strSelect As String = _
"SELECT * FROM Categories"
Dim da As SqlDataAdapter = New SqlDataAdapter(strSelect, cn)


' Load a data set.
Dim ds As DataSet = New DataSet( )
da.Fill(ds, "Categories")

到目前为止,代码运行良好,但只是为了更好地理解,我想问一下 虽然 SQL Server 数据库中的数据根据​​查询保存到da,但为什么我们需要将其保存/传输到数据集对象 ds 中。

除了速度之外,SqlCommandSqlDataAdapter 相比还有什么额外的好处吗?

Dim autogen As New SqlCommandBuilder(da)

Dim dt As DataTable = ds.Tables("Categories")

' Modify one of the records.
Dim row As DataRow = dt.Select("CategoryName = 'Dairy Products'")(0)
row("Description") = "Milk and stuff"

当我与

一起使用时会出错
da.Update(ds, "Categories")

关于 dt.select 不返回任何值。

  1. 出路是什么?

【问题讨论】:

    标签: sql sql-server vb.net ado.net database-table


    【解决方案1】:

    回答您的问题:

    您使用服务器资源管理器创建的表在内存中。数据集也是如此,它们是表的内存表示。至于您的第二个示例,当您尝试获取 DT 时,您使用的 DS 未填充。因此为什么 DT 是空的。

    如果您开始,我建议您查看 Linq-to-Sql (http://msdn.microsoft.com/en-us/library/bb425822.aspx) 以了解在 .net 中执行 sql 的最新方法(我认为它是 4.0 框架)

    至于第二点,我会说通常你应该对大多数 sql 命令使用存储过程.. sqlcommand 是这样使用的

    Try
      Cmd = New SqlClient.SqlCommand("st_InventoryStatus_Or_AnyStoreProcName_Or_ASqlQuery")
      Cmd.CommandTimeout = 300 'not really needed'
      Cmd.CommandType = CommandType.StoredProcedure 'you can type CommandType.Text here to use directly your "Select * from Category"'
      Cmd.Parameters.Clear() 'just to be sure its empty, its not mandatory'
      Cmd.Parameters.Add("@idCategory", SqlDbType.Int).Value = myCategory.Id 'here are the parameters of your store proc, or of your query ("select * from Category where Category.id = @Id")'
    
    
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Information)
    End Try
    

    【讨论】:

    • 关于使用服务器资源管理器创建的表在内存中,那么没有办法将它们保存在数据库中吗?
    • 我不完全理解您在这里解释的内容和内容(至于您的第二个示例,...);好吧,没有第二个示例它是单个代码的一部分(如果我之前不清楚的话)。为什么不会 da.Fill(ds, "Categories") 填充 ds 并且 dt 不为空。我可以像使用它显示表格值一样使用它。只有当我使用 select (dt.select) 和 update 时才会出错
    • 在此处查看正确使用数据适配器的方法:msdn.microsoft.com/en-us/library/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    相关资源
    最近更新 更多