在VB.NET中运行SQL Server查询

时间:2018-11-30 22:00:07

标签: sql-server vb.net

如何创建查询以返回数据库中的列? SQL select语句很简单。我在VB方面遇到了问题。

SELECT UserNO 
FROM UserTable 
WHERE UserID = user;

然后我需要获取该UserNO并将其传递给另一个T-SQL存储过程。我将如何运行SELECT查询并在Visual Basic中返回结果?

附上了我的一些代码。下面的代码将用户添加到数据库中,但是当在插入存储过程中运行INSERT语句时,SQL Server会自动生成UserNo(INTEGER),因此我需要在创建用户后拉出UserNO。

Public conwd As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")
Public conwp As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")

Dim cmdP As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwp)
Dim cmdD As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwd)

conmp.Open()
conmd.Open()

cmdP.ExecuteNonQuery()
cmdD.ExecuteNonQuery()

2 个答案:

答案 0 :(得分:0)

Using..End Using块关闭并处理可能包含非托管代码的数据对象。参数有助于防止SQL注入。

Private Sub OPCode2()
    Dim newID As Integer
    Dim sql = "Insert Into UserTable (User) Values (@User); Select SCOPE_IDENTITY();"
    Using cn As New SqlConnection("Your Connection String")
        Using cmd As New SqlCommand(sql, cn)
            cmd.Parameters.Add("@User", SqlDbType.NVarChar).Value = "Brian Weaver"
            cn.Open()
            newID = CInt(cmd.ExecuteScalar)
        End Using
    End Using
    'Use the newID in your next command
    UserStoredProcedure(newID)
End Sub

Private Sub UseStoredProcedure(id As Integer)
    Dim sql = "InsertSomeUserInfo" 'the name of your stored procedure
    Using cn As New SqlConnection("Your Connection String")
        Using cmd As New SqlCommand(sql, cn)
            cmd.CommandType = CommandType.StoredProcedure
            'whatever parameter names and types your stored procedure uses
            cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = id
            cmd.Parameters.Add("@Salary", SqlDbType.Decimal).Value = 50000
            cn.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
End Sub

答案 1 :(得分:0)

$client = new Client([
    'base_uri'=>'https://www.bulksms.com/',
    'timeout'=>'900.0'
]); 

//$result = $client->post('', [
//    'form_params' => [
//        'sample-form-data' => 'value'
//    ]
//]);

$result = $client->request('POST','https://api.bulksms.com/v1/messages', [
    'form_params' => [
        'username' => 'username',
        'password' => '****',
        'sender' => 'my appname',
        'recipients' => '+5555555555',
        'message' => 'Testing message',
    ]
]);

ExecuteScalar检索结果的第一行