在asp.net中怎么用VB连接SQL SERVER2005数据库

时间:2021-02-14 13:37:45

第一步:

Private Function ExecuteSQL(ByVal strSQL As String, ByRef errMsg As String) As DataSet 
        Dim cnn As SqlClient.SqlConnection 
        Dim cmd As New SqlClient.SqlCommand() 
        Dim adpt As SqlClient.SqlDataAdapter 
        Dim rst As New DataSet() 
        Dim SplitSQL() As String 
        errMsg = "" 
        Try 
            SplitSQL = Split(strSQL) 
            cnn = New SqlClient.SqlConnection("DataSource=192.168.0.1;Database=your_database;Uid=sa;Pwd=123123") 
             If InStr("INSERT,DELETE,UPDATE", UCase$(SplitSQL(0))) Then 
                cmd.Connection = cnn 
                cmd.Connection.Open() 
                cmd.CommandText = strSQL 
                cmd.ExecuteNonQuery() 
            Else 
                adpt = New SqlClient.SqlDataAdapter(strSQL, cnn) 
                adpt.Fill(rst) 
                ExecuteSQL = rst 
            End If 
        Catch ex As Exception 
            errMsg = ex.Message 
        Finally 
            rst = Nothing 
            cnn = Nothing 
        End Try 
    End Function 

第二步 调用:

GridView1.DataSource = ExecuteSQL("select * from tab'", "数据操作失败!") 
GridView1.DataBind() 

说明:ExecuteSQL()两个参数 1个是 SQL语句 另外一个是操作失败时的提示信息。直接在需要绑定数据的时候调用就是了。很简单那 。并不需要你的积分 只希望能帮到你