我的cmd.executenonquery vb程序错误

时间:2018-09-08 12:52:16

标签: vb.net

我遇到以下错误:

  

未处理的异常:System.Data.SqlClient.SqlException:'500'附近的语法不正确。
  在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔值breakConnection,Action 1 wrapCloseInAction)
  在System.Data.SqlClient.SqlInternalConnection.OnError(SqlException异常,布尔值breakConnection,Action`1 wrapCloseInAction)
  在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,布尔调用方HasConnectionLock,布尔asyncClose)
  在System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,Boolean&dataReady)
  在System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName,布尔异步,Int32超时,布尔asyncWrite)
  在System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1完成,字符串methodName,布尔型sendToPipe,Int32超时,布尔型和usedCache,布尔型asyncWrite,布尔型inRetry)
  在System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
  在G:\ 0000000SRIKANTH \ Projects \ VB \ database \ DATACONSOLE \ DATACONSOLE \ Module1.vb中的DATACONSOLE.Module1.Main()中:第70行

我的数据库表:

CREATE TABLE new
(
    [SNO] INT  PRIMARY KEY, 
    [SNAME] NCHAR(12) NULL, 
    [COURSE] NCHAR(10) NULL, 
    [TOTALMARKS] INT NULL DEFAULT 700, 
    [PERCENTAGEMARKS] DECIMAL(9, 2) NULL, 
    [GRADE] NCHAR(10) NULL
)

我的代码:

Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Sql

Module Module1

    Sub Main()

        Dim CON As SqlConnection
        Dim CMD As SqlCommand
        Dim SOURCE As String
        Dim COMMAND As String


        SOURCE = "Data Source=DESKTOP-20RTV69\SQLEXPRESS;Initial Catalog=VBONE;Integrated Security=True;Pooling=False"

        CON = New SqlConnection(SOURCE)

        CON.Open()
        Dim SNO As Integer
        Dim NAME As String
        Dim COURSE As String
        Dim MARKS As Integer
        Dim TOTAL As Integer = 700
        Dim PERCENTAGE As Double
        Dim GRADE As String


        Console.Write("ENTER SNO : ")
        SNO = Convert.ToInt32(Console.ReadLine())

        Console.Write("ENTER NAME : ")
        NAME = Console.ReadLine()

        Console.Write("ENTER COURSE : ")
        COURSE = Console.ReadLine()

        Console.Write("ENTER MARKS : ")
        MARKS = Convert.ToInt32(Console.ReadLine())

        PERCENTAGE = (MARKS / TOTAL) * 100


        If (PERCENTAGE > 90) Then
            GRADE = "'A'"
        ElseIf (PERCENTAGE > 70) Then
            GRADE = "'B'"
        ElseIf (PERCENTAGE > 60) Then
            GRADE = "'C'"
        ElseIf (PERCENTAGE > 50) Then
            GRADE = "'D'"
        Else
            GRADE = "'F'"
        End If

        COMMAND = "INSERT INTO NEW(SNO,NAME,COURSE,MARKSOBTAINED,PERCENTAGEMARKS,GRADE)
VALUES(" & SNO & " , '" & NAME & "' , '" & COURSE & "' " & MARKS & "," & PERCENTAGE & ",'" & GRADE & "')"

        CMD = New SqlCommand(COMMAND, CON)
        CMD.ExecuteNonQuery()
        Console.WriteLine("---RECORD IS INSERTED---")
        Console.ReadLine()

    End Sub

End Module

请您能找到解决我问题的方法,并给我一些不重复此类错误的建议。

2 个答案:

答案 0 :(得分:3)

您需要做的是使用SQL参数作为要传递给数据库的值。

这并不是要进行代码审查,但是在显示如何添加SQL参数时,我还指出了其他几点:

  • 通常使用lowerCamelCase作为变量名。
  • 将变量声明为接近给定值的位置。
  • 应进行某种类型的用户输入验证。
  • 代码应包含在一个目的区域中,例如您距使用连接的代码还有CON.Open()远。
  • 使用SqlConnectionStringBuilder可以更轻松地生成正确的连接字符串。在这种情况下,没有必要禁用连接池。

  • VB.NET中的Using构造用于确保在资源用完后释放非托管资源(.NET框架控制范围之外的内容)(即使出现问题) )。

所以,我想到了:

Option Infer On
Option Strict On

Imports System.Data.SqlClient

Module Module1

    Sub Main()

        ' Get the user input...
        Dim sno As Integer = -1
        Dim name As String = Nothing
        Dim course As String = Nothing
        Dim marksObtained As Integer = -1
        Dim maxPossibleMarks As Integer = 700

        While sno < 0
            Console.Write("ENTER SNO: ")
            Dim userInput = Console.ReadLine()
            If Not Integer.TryParse(userInput, sno) Then
                sno = -1
                Console.WriteLine("Please enter a number...")
            End If
        End While

        While String.IsNullOrWhiteSpace(name)
            Console.Write("ENTER NAME: ")
            name = Console.ReadLine()
            Console.WriteLine("Please enter the name...")
        End While

        While String.IsNullOrWhiteSpace(course)
            Console.Write("ENTER COURSE: ")
            course = Console.ReadLine()
            Console.WriteLine("Please enter the course...")
        End While

        While marksObtained < 0
            Console.Write("ENTER MARKS: ")
            Dim userInput = Console.ReadLine()
            If Not Integer.TryParse(userInput, marksObtained) Then
                marksObtained = -1
                Console.WriteLine("Please enter a number...")
            End If
        End While

        ' Process the user input...
        Dim percentageMarks = (marksObtained / maxPossibleMarks) * 100

        Dim grade As String

        If percentageMarks > 90 Then
            grade = "'A'"
        ElseIf percentageMarks > 70 Then
            grade = "'B'"
        ElseIf percentageMarks > 60 Then
            grade = "'C'"
        ElseIf percentageMarks > 50 Then
            grade = "'D'"
        Else
            grade = "'F'"
        End If

        ' Save the information to the database...
        Dim csb As New SqlConnectionStringBuilder With {
            .DataSource = "DESKTOP-20RTV69\SQLEXPRESS",
            .InitialCatalog = "VBONE",
            .IntegratedSecurity = True}

        Using conn As New SqlConnection(csb.ConnectionString)
            Dim sql = "INSERT INTO NEW(SNO, NAME, COURSE, MARKSOBTAINED, PERCENTAGEMARKS, GRADE) VALUES(@sno, @name ,@course, @marksObtained, @percentageMarks, @grade)"

            Using sqlCmd As New SqlCommand(sql, conn)
                sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "@sno", .SqlDbType = SqlDbType.Int, .Value = sno})
                sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "@name", .SqlDbType = SqlDbType.NChar, .Size = 12, .Value = name})
                sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "@course", .SqlDbType = SqlDbType.NChar, .Size = 10, .Value = course})
                sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "@marksObtained", .SqlDbType = SqlDbType.Int, .Value = marksObtained})
                sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "@percentageMarks", .SqlDbType = SqlDbType.Decimal, .Precision = 9, .Scale = 2, .Value = percentageMarks})
                sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "@grade", .SqlDbType = SqlDbType.NChar, .Size = 10, .Value = grade})

                conn.Open()
                sqlCmd.ExecuteNonQuery()

            End Using

        End Using

        Console.WriteLine("---RECORD IS INSERTED---")
        Console.ReadLine()

    End Sub

End Module

代码中有机会检查marksObtained <= maxPossibleMarks

顺便说一句,计算值实际上不应存储在数据库中(PERCENTAGEMARKS和GRADE列)-从测试中您会知道是否存在某些性能问题需要这样做。最大可能的分数应该已经存储在数据库中,并且可能是获得分数的日期。

答案 1 :(得分:-1)

似乎您在执行命令“ course”和“ mark”之间忘记了逗号。一定是这样的:

COMMAND = "INSERT INTO NEW(SNO,NAME,COURSE,MARKSOBTAINED,PERCENTAGEMARKS,GRADE)VALUES(" & SNO & " , '" & NAME & "' , '" & COURSE & "', " & MARKS & "," & PERCENTAGE & ",'" & GRADE & "')"