Dim con As New System.Data.SqlClient.SqlConnection
con.ConnectionString = "Server=iraq\\sqlexpress ; Database=stats ; Trusted_Connection=True ;"
Dim com开发者_运维技巧 As New System.Data.SqlClient.SqlCommand
com.CommandText = "insert into users values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "')"
com.Connection = con
con.Open()
com.ExecuteNonQuery()
con.Close ()
There are new events happen when i adjust the connection string
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite2\App_Data\stats.mdf;Integrated Security=True;User Instance=True"
show me error with com.ExecuteNonQuery()
any suggestion ?
Can't speak to your connection String. Looks rather arduous. Beyond that, I see a few problems:
A. This is the most obvious to me: Your INSERT statement is incorrect. Try THIS:
INSERT INTO your_table_name (column_name_1, column_name_2, . . .) VALUES (value_1, value_2, . . .)
B. Extend the above, in keeping with the comments of others, and properly PARAMETERIZE your query. Further, make use of the Application Settings file for your connection string, instead of hardcoding it into your app. Last, employ a Using block, for the connection and command objects - this will handle initialization and Disposal of these. I stripped the following out of an old project of mine - hopefully I didn't muff any sytax adapting it for this post. The original code ran against a Stored Procedure in the SQL Server back-end:
Public Overridable Sub DataINSERT() Implements IAppUser.DataINSERT 'tblAppUser
Dim CommandText As String = "INSERT INTO tblUser(UserName, PassWord, Enabled) VALUES(@UserName, @PassWord, @Active)"
'The Connection String can be established in your Project Settings file:
Using cn As New SqlClient.SqlConnection(My.Settings.MyDataConnectionString)
Using cmd As New SqlClient.SqlCommand(CommandText, cn)
cmd.CommandType = CommandType.Text
'INSERT PARAMETER SET_UP:
Dim prmUserName As New SqlClient.SqlParameter("@UserName", SqlDbType.VarChar, 50)
prmUserName.Direction = ParameterDirection.Input
prmUserName.Value = _UserName
cmd.Parameters.Add(prmUserName)
Dim prmPassWord As New SqlClient.SqlParameter("@PassWord", SqlDbType.VarChar, 50)
prmPassWord.Direction = ParameterDirection.Input
prmPassWord.Value = _PassWord
cmd.Parameters.Add(prmPassWord)
Dim prmActive As New SqlClient.SqlParameter("@Active", SqlDbType.Bit, 0)
prmActive.Direction = ParameterDirection.Input
prmActive.Value = _Active
cmd.Parameters.Add(prmActive)
Try
cn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Dim str As String = Me.ToString & ": " & ex.Message & " / " & ex.TargetSite.ToString
MsgBox(str)
End Try
End Using
End Using
End Sub 'DataINSERT tblAppUser
My final comment would be to check out Stored Procedures with SQL Server. Let me know if any of this doesn't make sense.
精彩评论