我使用下面给出的Web服务从数据库获取数据。在该代码中,它具有静态字符串连接和字符串查询。我使用相同的Web服务来实现多种功能。我需要手动给出字符串查询和字符串连接,以避免多次使用相同的代码,而不是使用相同的函数。是否可以在运行时提供字符串连接和字符串查询。
这是代码。
<WebMethod()> _
Public Function GetData() As String
Dim sqlcon As New SqlClient.SqlConnection
Dim sqlcmd, cmd As SqlClient.SqlCommand
Dim objeDS, objeDS1 As DataSet
Dim adpp, adpp1 As SqlClient.SqlDataAdapter
Dim dt, dt1 As DataTable
Dim pack_tbl As New DataTable
sqlcon.ConnectionString = ConfigurationManager.AppSettings("constr")
sqlcon.Open()
sqlcmd = New SqlClient.SqlCommand()
sqlcmd.Connection = sqlcon
sqlcmd.CommandType = CommandType.Text
sqlcmd.CommandText = "sqlcommand"
objeDS = New DataSet()
adpp = New SqlClient.SqlDataAdapter()
adpp.SelectCommand = sqlcmd
adpp.Fill(objeDS)
sqlcon.Close()
dt = New DataTable()
dt = objeDS.Tables(0)
Return objeDS.GetXml()
'Return "Welcome"
End Function
答案 0 :(得分:0)
尝试此代码可以帮助您。
VB代码
<WebMethod()> _
Public Function GetData(ByVal strQuery As String, ByVal strCon As String) As String
Dim dt As New DataTable()
dt.Clear()
Using conn As New System.Data.SqlClient.SqlConnection()
conn.ConnectionString = ConfigurationManager.ConnectionStrings(strCon).ConnectionString
Using cmd As New System.Data.SqlClient.SqlCommand()
cmd.CommandText = strQuery
cmd.Connection = conn
conn.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object)
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)()
For Each col As DataColumn In dt.Columns
row.Add(col.ColumnName, dr(col))
Next
rows.Add(row)
Next
Return serializer.Serialize(rows)
End Using
End Using
End Function