简体   繁体   English

如何在VB.Net中删除空白

[英]How to remove white space in VB.Net

In the following code SqlDataReader 'dr' does not read the "SubjectCode" of subjects whose names contain white space; 在下面的代码中,SqlDataReader'dr'不会读取名称包含空格的主题的“ SubjectCode”; example English Language, Social Studies, Principles of Cost Accounting, etc. from the subjects table. 例如,主题表中的英语,社会研究,成本会计原理等。

I'd therefore be more than grateful if someone could very kindly help me out immediately. 因此,如果有人可以立即很好地帮助我,我将不胜感激。

cmd = New SqlCommand( _
    "select subjectCode from ProgramDetails.subjects where subjectname='" & _
    Trim(subname) & " ' ", cn)
dr = cmd.ExecuteReader
If dr.Read Then
    subcode = dr(0)
End If
dr.Close()
  1. You're open for SQL-Injection , use SQL-Parameters 您可以使用SQL-Parameters进行SQL注入
  2. You have a white-space at the end, i assume that this is not desired 您最后有一个空格,我认为这是不希望的
  3. You might want to use LIKE with the wildcard % instead: 您可能希望将LIKE与通配符%使用:

For example: 例如:

Dim sql = "Select subjectCode From ProgramDetails.subjects where subjectname Like @subname"
Using con = New SqlConnection(connectionString)
    Using cmd = New SqlCommand(sql, con)
        cmd.Parameters.AddWithValue("@subname", String.Format("%{0}%", "english"))
        Con.Open()
        Using rd = cmd.ExecuteReader()
            While rd.Read()  
                Dim subjectCode = rd.GetString(0)
                ' ... '
            End While
        End Using
    End Using
End Using

Just use the RTRIM 只需使用RTRIM

cmd = New SqlCommand("select RTRIM(subjectCode) from ProgramDetails.subjects " + _
                     "where subjectname Like '" & Trim(subname) & "%'", cn)
dr = cmd.ExecuteReader
If dr.Read Then
    subcode = dr(0)
End If
dr.Close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM