Dim sql = 从ProgramDetails.subjects中选择subjectCode,其中主题名如@subname 使用 con = 新 SqlConnection( 数据源= EBENEZERAKAGLO\SQLEXPRESS;初始目录= Naass;集成安全性=真) 使用 cmd = 新 SqlCommand(sql,con) cmd.Parameters.AddWithValue( @ subname,字符串 .F ormat( %{0}%, )) con.Open() 使用 rd = cmd.ExecuteReader() while rd.Read() Dim subjectCode = rd.GetInt32( 0 ) subcode = subjectCode ' ...' MsgBox(subjectCode) 结束 虽然 结束 使用 结束 使用 结束 使用 解决方案 RTRIM [ ^ ]和/或 LTRIM [ ^ ]。 或者你可以使用 String.Trim [ ^ ] 1。在Form Load事件期间不要从子名称变量中删除空格。 subname = Module1.sname 2. String.Format(%{0}%,)创建一个包含 %%的字符串参数。与LIKE运算符一起使用,它将匹配数据库中的所有内容。请将该行代码更改为: cmd.Parameters.AddWithValue(@ subname,subname) 3.将SQL语句更改为此。 Dim Sql =从ProgramDetails.subjects中选择subjectCode,其中subjectname = @ subname; In the following code all the subject codes are read by SQLDataReader rd. How do I make the DataReader read the subject code of only the selected subject regardless of whether the subject name contain white space or not such as Biology, English Language, Principles of Cost Accounting, etc?Dim sql = "Select subjectCode From ProgramDetails.subjects where subjectname like @subname" Using con = New SqlConnection("Data Source=EBENEZERAKAGLO\SQLEXPRESS;Initial Catalog=Naass;Integrated Security=True") Using cmd = New SqlCommand(sql, con) cmd.Parameters.AddWithValue("@subname", String.Format("%{0}%", "")) con.Open() Using rd = cmd.ExecuteReader() While rd.Read() Dim subjectCode = rd.GetInt32(0) subcode = subjectCode ' ... ' MsgBox(subjectCode) End While End Using End Using End Using 解决方案 RTRIM[^] And/Or LTRIM[^] in your SQL statement.Alternatively you could use String.Trim[^]1. Do not remove spaces from the subname variable during the Form Load event.subname = Module1.sname2. String.Format("%{0}%", "") creates a string parameter that contains %%. Used with the LIKE operator, it will match everything in the database. Please change that line of code to this:cmd.Parameters.AddWithValue("@subname", subname)3. Change the SQL statement to this.Dim Sql = "Select subjectCode From ProgramDetails.subjects where subjectname=@subname;" 这篇关于如何在VB.NET中删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-23 22:28