AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 76954366
Accepted
dpresnell90
dpresnell90
Asked: 2023-08-22 22:35:15 +0800 CST2023-08-22 22:35:15 +0800 CST 2023-08-22 22:35:15 +0800 CST

Sintaxe incorreta próxima ao erro 'C:' no aplicativo Microsoft VB Console

  • 772

No momento, estou enfrentando um erro ao testar e depurar meu programa de aplicativo de console VB.NET que fiz círculos tentando resolver. Ao executar o código do programa, continuo recebendo o erro Incorrect Syntax Near 'C:'. Também tentei especificar um local de unidade diferente na tentativa de ver se recebo o mesmo erro, e recebo com a letra de unidade especificada.

Examinei a sintaxe do meu programa, verifiquei o código e também estudei os detalhes da pilha de erros e não consigo encontrar nenhuma resolução.

abaixo está meu código:

Imports System.Data
Imports System.Data.SqlClient


Public Module Module1

Public GBTBBreak As Single = 1099511627776
Public GBDivisor As Single = 1024 * 1024 * 1024 * 1.0
Public TBDivisor As Single = GBDivisor * 1024

Dim dt As New DataTable("DriveInformation")

Public Function FormatForGBTB(input As Single) As String
    If input < GBTBBreak Then

        Return String.Format("{0,15} {1}", input / GBDivisor, "GB")
    Else
        Return String.Format("{0,15} {1}", input / TBDivisor, "TB")
    End If
End Function

Public Sub Main()

    'Dim dt As New DataTable("DriveInformation")

    dt.Columns.Add(New DataColumn("Date"))
    dt.Columns.Add(New DataColumn("Server"))
    dt.Columns.Add(New DataColumn("Drive"))
    dt.Columns.Add(New DataColumn("TotalSpace"))
    dt.Columns.Add(New DataColumn("UsedSpace"))
    dt.Columns.Add(New DataColumn("RemainingSpace"))
    dt.Columns.Add(New DataColumn("GBorTBDrive"))
    dt.Columns.Add(New DataColumn("DriveActiveStatus"))

    ' Get information and Write to Console.
    Dim Host As String = System.Net.Dns.GetHostName
    Console.WriteLine("Server Name: {0}", Host)
    Console.WriteLine("Date: {0}{1}", DateTime.Now.ToString("yyyy/MM/dd h:mm:ss tt"), vbCrLf)


    Dim allDrives() As IO.DriveInfo = IO.DriveInfo.GetDrives()

    For Each d As IO.DriveInfo In allDrives.Where(Function(dr) dr.IsReady)


        Console.WriteLine(d.Name.Remove(2))
        Console.WriteLine("  Drive type: {0}", d.DriveType)
        Console.WriteLine("  Volume label: {0}", d.VolumeLabel)
        Console.WriteLine("  File system: {0}", d.DriveFormat)
        Console.WriteLine("  Total size of drive:   {0}", FormatForGBTB(d.TotalSize))
        Console.WriteLine("  Total used space:      {0}", FormatForGBTB(d.TotalSize - d.TotalFreeSpace))
        Console.WriteLine("  Total available space: {0}", FormatForGBTB(d.TotalFreeSpace))
    Next

    ' Put Information into DataTable
    For Each d In allDrives
        ' The DriveNumber check was NOT NEEDED, added a bunch of extra code

        Dim divisor As Double = If(d.TotalSize < GBTBBreak, GBDivisor, TBDivisor)

        Dim row As DataRow = dt.NewRow

        row("Date") = DateTime.Now.ToString("yyyy/MM/dd h:mm:ss tt")
        row("Server") = System.Net.Dns.GetHostName
        row("Drive") = d.Name.Remove(1, 2)
        row("TotalSpace") = FormatNumber(d.TotalSize / divisor).ToString()
        row("UsedSpace") = FormatNumber((d.TotalSize - d.TotalFreeSpace) / divisor).ToString()
        row("RemainingSpace") = FormatNumber(d.TotalFreeSpace / divisor).ToString()
        row("GBorTBDrive") = If(d.TotalSize < GBTBBreak, "GB", "TB")
        row("DriveActiveStatus") = d.IsReady
        dt.Rows.Add(row)

    Next

    ' Write Information to XML file

    Dim day As String = DateTime.Now.ToString("yyyy" & Space(1) & "MM" & Space(1) & "dd" & Space(1) & "h" & Space(1) & "mm" & Space(1) & "tt")

    Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    path = IO.Path.Combine(path, "ServerStorageC7L6M72" & Space(1) & day & Space(1) & ".xml")

    dt.WriteXml(path)

    ReadXmlContents()

End Sub
Public Sub ReadXmlContents()
    Dim day As String = DateTime.Now.ToString("yyyy" & Space(1) & "MM" & Space(1) & "dd" & Space(1) & "h" & Space(1) & "mm" & Space(1) & "tt")

    Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    path = IO.Path.Combine(path, "ServerStorageC7L6M72" & Space(1) & day & Space(1) & ".xml")

    dt.ReadXml(path)



    Dim ServerCheckConnectString = "Data Source=localhost;Initial Catalog=ServerDriveStorageChecks;Persist Security Info=True;User ID=test;Password=*****"


    Dim SQL As String =
        "INSERT INTO DriveInformation(Date, Server, Drive, TotalSpace, UsedSpace, RemainingSpace, GBorTBDrive, DriveActiveStatus) " &
     "Select MY_XML.DriveInformation.query('Date').value('.', 'DATETIME') " &
     ",MY_XML.DriveInformation.query('Server').value('.', 'VARCHAR(15)') " &
     ",MY_XML.DriveInformation.query('Drive').value('.', 'VARCHAR(1)') " &
     ",MY_XML.DriveInformation.query('TotalSpace').value('.', 'NUMERIC(10,2)') " &
     ",MY_XML.DriveInformation.query('UsedSpace').value('.', 'NUMERIC(10,2)') " &
     ",MY_XML.DriveInformation.query('RemainingSpace').value('.', 'NUMERIC(10,2)') " &
     ",MY_XML.DriveInformation.query('GBorTBDrive').value('.', 'VARCHAR(2)') " &
     ",MY_XML.DriveInformation.query('DriveActiveStatus').value('.', 'VARCHAR(6)') " &
     "FROM ( " &
     "SELECT CAST(MY_XML AS xml) " &
     "FROM OPENROWSET (BULK " & path & ", SINGLE_BLOB) AS T(MY_XML)) AS T(MY_XML) CROSS APPLY MY_XML.nodes('DocumentElement/DriveInformation') AS MY_XML (DriveInformation) "

    Dim cn As SqlConnection
    Dim cmd As SqlCommand


    cn = New SqlConnection(ServerCheckConnectString)
    cmd = New SqlCommand(SQL, cn)

    cn.Open()
    cmd.ExecuteNonQuery()




    ' Connection is closed/disposed here, *even if an exception is thrown*
End Sub
End Module

E abaixo os detalhes do erro são copiados:

  System.Data.SqlClient.SqlException
  HResult=0x80131904
  Message=Incorrect syntax near 'C:'.
  Source=Core .Net SqlClient Data Provider
  StackTrace:
  at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean 
  breakConnection, Action`1 wrapCloseInAction) in 
  /_/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnection.cs:line 1352
  at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject 
  stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) in 
  /_/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs:line 1140
  at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand 
  cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, 
  TdsParserStateObject stateObj, Boolean& dataReady) in 
  /_/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs:line 2172
  at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean 
  async, Int32 timeout, Boolean asyncWrite) in 
  /_/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs:line 2421
  at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 
  completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName) 
  in /_/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs:line 1176
  at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() in 
  /_/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs:line 874
  at HDD_Drive_Information_Console_App.Module1.ReadXmlContents() in C:\Users\daniel 
  presnell\source\repos\HDD Drive Information Console App Rev 6  06-26-2023\HDD Drive 
  Information Console App\Program.vb:line 155
  at HDD_Drive_Information_Console_App.Module1.Main() in C:\Users\daniel 
  presnell\source\repos\HDD Drive Information Console App Rev 6  06-26-2023\HDD Drive 
  Information Console App\Program.vb:line 113

Consigo gravar com êxito as informações do aplicativo de console em um arquivo XML. Eu executei manualmente uma consulta com o arquivo XML também em minha tabela de dados e ele lê e importa as informações perfeitamente para minha instância localhost do SQLServer a esse respeito. Acredito que o problema esteja no programa que lê o arquivo XML na tabela de dados.

Ainda não sou o mais versado em consultas SQL ou programação, então estou supondo que tenho uma sintaxe incorreta que estou perdendo.

Obrigado pela sua avaliação sobre este assunto.

Os créditos e agradecimentos também vão para Joel Coehoorn por otimizar o código de sua iteração anterior!

sql-server
  • 1 1 respostas
  • 27 Views

1 respostas

  • Voted
  1. Best Answer
    Malcolm McCaffery
    2023-08-22T22:43:00+08:002023-08-22T22:43:00+08:00

    Este erro sugere que sua sintaxe SQL está incorreta. Você deve verificar isso, parece que o caminho não está entre aspas simples, ou seja

    (BULK " & path & ",
    

    deveria estar

    (BULK '" & path & "',
    

    Você pode verificar o comando SQL final gerado e testar se pode executá-lo no servidor SQL com uma ferramenta como o SQL Management Studio. Dessa forma, você pode obter o comando SQL correto e garantir que seu aplicativo esteja usando o mesmo.

    • 1

relate perguntas

  • Não consigo conectar o SQL Server no VS Code

  • Compare os dados de duas tabelas com base na coluna-chave e obtenha um relatório personalizado

  • O loop no TSQL e a instrução de atualização não funcionam

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve