首页 > 解决方案 > 如何制作一个读取 SQL Server 单行的所有列并且输出是向量的函数

问题描述

大家好,我是 VB.net 和 SQL 世界的菜鸟。

我想编写一个函数,它的输出是一个向量,其中包含所选行的列的值。

我想做一个输入是查询的公共函数

对于这个特定示例,我的查询是:

"Select idcliente, Name, Lastname, from Clients where Celphone = '" + txtcelphone.Text + "'"
Public Function RunQuery_read_row(Query As String)    
    Try        
        Dim SQLCmd As New SqlCommand(Query, SQLcon)

        return  'The return should be a vector whose size will be adapted according to the query"
    Catch ex As Exception        
    End Try

End Function

这个函数将从一个表单中调用,该表单有几个文本框,函数的结果将被记录下来。

谢谢您的帮助

最好的问候, FBello

标签: sql-servervb.net

解决方案


连接字符串以在 Sql Server 中执行是非常不明智的。除了很难获得所有单引号和正确的事实之外,它还可能通过 Sql 注入损坏您的数据库。始终使用参数。我不得不猜测 .Add 方法中参数的数据类型和大小。检查您的数据库以获取正确的值。

我刚刚将参数的值传递给函数。函数需要返回类型。由于我不知道您所说的“向量”是什么意思,所以我使用了 DataTable。

将您的数据库对象保留在使用它们的方法的本地,以便确保它们已关闭和处置。Using...End Using 块会为您执行此操作,即使存在错误也是如此。

Public Class DataAccess
    Private Shared conStr As String = "Your connection string"
    Public Shared Function GetClientByPhone(phone As String) As DataTable
        Dim dt As New DataTable
        Using cn As New SqlConnection(conStr),
                cmd As New SqlCommand("Select idcliente, Name, Lastname from Clients where Celphone = @Phone", cn)
            cmd.Parameters.Add("@Phone", SqlDbType.VarChar, 50).Value = phone
            cn.Open()
            dt.Load(cmd.ExecuteReader)
        End Using
        Return dt
    End Function
End Class

在表格...

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim dt As DataTable
    Try
        dt = DataAccess.GetClientByPhone(TextBox1.Text)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
        Exit Sub
    End Try
    TextBox2.Text = dt(0)(0).ToString
    TextBox3.Text = dt(0)(1).ToString
    TextBox4.Text = dt(0)(2).ToString
End Sub

我将 Try...End Try 移至表单代码,以便在出现错误时向用户显示消息框。不要写一个空的 Catch。你的代码会吞下错误。


推荐阅读