0

當我調試我的網站的代碼時出現此錯誤。我的目標是將數據插入SQL Server 2008數據庫。Visual Studio和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異常,布爾breakConnection)+2030802
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException異常,布爾breakConnection)+5009584
System.D ata.SqlClient.TdsParser.ThrowExceptionAndWarning()234
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior,SqlCommand的cmdHandler,SqlDataReader的數據流,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 

由於該代碼源。

回答

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 
+0

它的工作:)非常感謝。 – user2649088

相關問題