После подключения к доступу строка не может объединиться - PullRequest
0 голосов
/ 10 апреля 2019

Я использую VB.net для создания программы, функция поиска данных из Access, а затем сохранения данных в HTML-файл.

Но когда после поиска данных из Access, строка не может объединиться.

    Dim strpath As String = System.Windows.Forms.Application.StartupPath + "\\output\\"
    If (Not System.IO.Directory.Exists(strpath)) Then
        System.IO.Directory.CreateDirectory(strpath)
    End If
    Dim strfilename As String = strpath + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + "_" + textBox_name.Text + ".html"

    Dim screach_name As String = textBox_name.Text
    Dim html_code As String = ""

    html_code += "<!DOCTYPE html><html><head><title>"
    html_code += screach_name
    html_code += "</title></head><body>"
    html_code += "Screach:<b>" + screach_name + "</b><br />"
    Try

        Dim strcon As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=data.mdb;"
        Dim con_db As OleDbConnection = New OleDbConnection(strcon)

        Dim sql_count As String = "SELECT COUNT(*) FROM table where name Like '%" + search_name + "%'"
        Dim com_data As OleDbCommand = New OleDbCommand(sql_count, con_db)
        Dim count_data As Integer = Convert.ToInt32(com_data.ExecuteScalar())
        html_code += "Number of records = "
        html_code += count_data.ToString


    Catch ex As Exception

    Finally

    End Try
        html_code += "</body></html>"


    Using file As StreamWriter = New StreamWriter(strfilename, True)
        file.WriteLine(html_code)
    End Using

Но вывод html только

Blockquote

<!DOCTYPE html> <html>  <head>  <title>
screach_name
    </title>    </head> <body>
Screach:    <b>  screach_name   </b>    <br />

Blockquote

1 Ответ

0 голосов
/ 11 апреля 2019

В вашем методе происходит 3 разные вещи.Ваш код будет легче отслеживать, поддерживать и тестировать, если разбить его на 3 различных метода.Обратите внимание, что продемонстрированные методы не связаны с пользовательским интерфейсом (нет прямых ссылок на textBox_name.Text).Это может пригодиться, если вы реструктурируете свое приложение и переместите, например, метод GetRecordCount в класс DataAccess.

Блоки Using ... End Using в методе GetRecordCount гарантируют, что ваши объекты базы данных закрыты иутилизируется даже при наличии ошибки.

StringBuilder в методе BuildHTMLString сохраняет форму программы, создавая и выбрасывая строки.Каждый раз, когда вы изменяете строку любым способом, программа должна выбросить старую строку и создать совершенно новую.

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim RecordCount = GetRecordCount(textBox_name.Text)
    Dim HTMLString = BuildHTMLString(RecordCount, textBox_name.Text)
    SaveHTMLString(HTMLString, textBox_name.Text)
End Sub

Private Function GetRecordCount(SearchName As String) As Integer
    Dim RecordCount As Integer
    'Pass the connection string directly to the constructor of the connection
    Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=data.mdb;")
        'Pass the query text an the connection directly to the constructor of the command
        Using cmd As New OleDbCommand("SELECT COUNT(*) FROM table where name Like @SearchName;", cn)
            'Always use parameters
            cmd.Parameters.Add("@SearchName", OleDbType.VarChar).Value = "%" & SearchName & "%"
            RecordCount = CInt(cmd.ExecuteScalar())
        End Using
    End Using
    Return RecordCount
End Function

Private Function BuildHTMLString(RecordCount As Integer, SearchName As String) As String
    Dim HTMLString As String = ""
    Dim sb As New StringBuilder()
    sb.AppendLine("<!DOCTYPE html><html><head><title>")
    sb.AppendLine(SearchName)
    sb.AppendLine("</title></head><body>")
    sb.AppendLine("Screach:<b>" & SearchName & "</b><br />")
    sb.AppendLine("Number of records = " & RecordCount.ToString)
    sb.AppendLine("</body></html>")
    HTMLString = sb.ToString
    Return HTMLString
End Function

Private Sub SaveHTMLString(HTML As String, SearchName As String)
    'Add Imports System.IO to the top or the file
    'Using Path.Combine makes sure the back slashes are OK
    Dim strpath As String = Path.Combine(Application.StartupPath, "\output\")
    If (Not Directory.Exists(strpath)) Then
        Directory.CreateDirectory(strpath)
    End If
    Dim HTMLFileName As String = DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") & "_" & SearchName & ".html"
    Dim strfilename As String = Path.Combine(strpath, HTMLFileName)
    Using file As StreamWriter = New StreamWriter(strfilename, True)
        file.WriteLine(HTML)
    End Using
End Sub
...