【问题标题】:Error with Visual Studio and SQL Server 2008Visual Studio 和 SQL Server 2008 出错
【发布时间】:2013-08-03 17:44:04
【问题描述】:

我在调试网站代码时收到此错误。我的目标是将数据插入 SQL Server 2008 数据库。

来源错误:

    objcnd.Parameters.Add(New SqlParameter("@username", strun))
    Ligne 22 :         objcnd.Parameters.Add(New SqlParameter("@password", strpw))
    Ligne 23 :         objcnd.ExecuteNonQuery()
    Ligne 24 :         'close connection
    Ligne 25 :         objconnection.Close()

错误

[SqlException (0x80131904): '?' 附近的语法不正确。]
System.Data.SqlClient.SqlConnection.OnError(SqlException 异常, Boolean breakConnection) +2030802
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException 异常, Boolean breakConnection) +5009584
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2275
.....

vb.net编写的代码源

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

Partial Class index
   Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button1.Click
    Dim strun As String = Request.Form("username")
    Dim strpw As String = Request.Form("password")

    Dim objconnection As SqlConnection = Nothing
    Dim objcnd As SqlCommand = Nothing
    Dim strconnection As String, strSQL As String
    'connection string 
    strconnection = ("Data Source=myPC-PC;Database=mytempDB;Integrated Security=true ")
    objconnection = New SqlConnection(strconnection)
    objconnection.ConnectionString = strconnection
    objconnection.Open()
    strSQL = "insert into userTD(username,password) values(?,?)"
    objcnd = New SqlCommand(strSQL, objconnection)
    objcnd.Parameters.Add(New SqlParameter("@username", strun))
    objcnd.Parameters.Add(New SqlParameter("@password", strpw))
    objcnd.ExecuteNonQuery()
    'close connection
    objconnection.Close()
    Response.Write("Entered Successfully ! ")

End Sub
End Class

提前致谢。

【问题讨论】:

    标签: vb.net visual-studio-2010 sql-server-2008 web-site-project


    【解决方案1】:

    对SqlClient引擎使用与参数同名的占位符

    strSQL = "insert into userTD(username,password) values(@username,@password)"
    

    另外,我建议您使用using statement 进行连接(对所有一次性对象都更好,但是如果您遇到异常并且它保持打开状态,则连接是一个大问题)

    Using objconnection = New SqlConnection(strconnection)
       ......
    
       objcnd.ExecuteNonQuery()
    
       ' No need to close explicititly the connection, ' 
       ' the following End Using statement takes care of that'
       ' also in case of exceptions.....'
    End Using
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多