在示例中,我有如下字符串:
[oledb] ; 此行之后的所有内容都是 OLE DB initstring
Provider=SQLOLEDB.1;Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=BMC;Data Source=
。
我想要 vb 2005 中的子字符串密码和用户 ID。
怎么做 ?
我需要的结果:Password=123456 and User ID=sa
。
由于这是一个连接字符串,您应该能够使用OleDbConnectionStringBuilder
它来解析它。
一个例子是这样的:
Dim builder As New OleDbConnectionStringBuilder(connectionString)
' builder("User ID") contains User ID
' builder("Password") contains Password
如果你想用老式的字符串解析来做,那么:
Dim data As String = "[oledb] ; Everything after this line is an OLE DB initstring" & vbCrLf _
& "Provider=SQLOLEDB.1;Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=BMC;Data Source="
Dim password As String = ""
Dim userID As String = ""
Dim semiColonIndex As Integer
Dim passIndex As Integer = data.IndexOf("Password=")
If passIndex > 0 Then
semiColonIndex = data.IndexOf(";", passIndex)
If semiColonIndex > 0 Then
password = data.Substring(passIndex + "Password=".Length, semiColonIndex - passIndex - "Password=".Length)
Debug.Print(password)
End If
End If
Dim userIndex As Integer = data.IndexOf("User ID=")
If userIndex > 0 Then
semiColonIndex = data.IndexOf(";", userIndex)
If semiColonIndex > 0 Then
userID = data.Substring(userIndex + "User ID=".Length, semiColonIndex - userIndex - "User ID=".Length)
Debug.Print(userID)
End If
End If
试试下面的方法,它会帮助你...
对于 SQL Connection 使用SQLClient
然后尝试如下...
Imports System.Data.SqlClient
Dim constring As String
constring = "Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=BMC;Data Source="
Dim builder As New SqlConnectionStringBuilder(constring)
Console.WriteLine("Username : " + builder.UserID)
Console.WriteLine("Password : " + builder.Password)
通过使用OLEDB Provider
然后尝试如下...
Imports System.Data.OleDb
Dim oledbbuilder As New OleDbConnectionStringBuilder("Provider=SQLOLEDB.1;Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=BMC;Data Source=")
Console.WriteLine("Username : " + oledbbuilder("User ID").ToString)
Console.WriteLine("Password : " + oledbbuilder("Password").ToString)