[英]Cant save or update my SQL Server tables using vb.net
我是.net的完整入门者,对一些基本知识感到困惑。 请帮忙。
首先,一旦我重新启动计算机,我创建并填充的表(通过在服务器资源管理器中右键单击表)就会消失。 我如何保留它们。
在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中。
除了速度之外, SqlCommand
比SqlDataAdapter
还有其他好处?
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不返回任何值。
回答您的问题:
使用服务器资源管理器创建的表处于“内存中”状态。 数据集也是如此,它们是表的内存表示形式。 对于第二个示例,尝试获取DT时不会填充您使用的DS。 因此,为什么DT为空。
如果您是从入门开始,我建议您研究一下Linq-to-Sql( http://msdn.microsoft.com/en-us/library/bb425822.aspx ),以获得在SQL中执行sql的最新方法。 .net(我认为它是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.