What i'm trying to do is that from a ASP.NET (framework 4) a user shall be able to update an existing record in a SQL Database using the record Key. USING Visual Studio 2010 (vb)
I get an error of Syntax near " \ ", i have 2 textboxes:
1- For the key
2-contains the information that would be sent to the SQL server in order to update such column (Control_ClosedByRev)
Dim Con As New SqlConnection
Dim SQL As String
Dim com As SqlCommand = Con.CreateCommand
Dim KeyID As Integer
KeyID = TextBox1_UpdateDataReview.Text
Con.ConnectionString = "Data Source=WCRDUSMJEMPR9\SQLEXPRESS;Initial Catalog=MicroDB;Integrated Security=True"
Con.Open()
SQL = "UPDATE ControlCharts set Control_ClosedByRev=" & TextBox2_UpdateDataReview.Text & " where ID_ControlCharts= " & KeyID
Dim cmd As New SqlCommand(SQL, Con)
'cmd.ExecuteScalar()
cmd.ExecuteNonQuery()
Label1_UpdateDataReview.Text = "Record Updated"
i tried changing the cmd.execute, it did not work. Thanks in advance.
First off, this is quite vulnerable to SQL Injection -- read into that and use parameterized queries instead.
Here is some sample code to help.
Con.ConnectionString = "Data Source=WCRDUSMJEMPR9\\SQLEXPRESS;Initial Catalog=MicroDB;Integrated Security=True"
Con.Open()
SQL = "UPDATE ControlCharts set Control_ClosedByRev=#ClosedByRev where ID_ControlCharts=#Key"
Dim cmd As New SqlCommand(SQL, Con)
cmd.Parameters.AddWithValue("#ClosedByRev ", TextBox2_UpdateDataReview.Text)
cmd.Parameters.AddWithValue("#Key", KeyID)
cmd.ExecuteNonQuery()
Good luck.
Try this: put "#" symbol before the the string
Con.ConnectionString = #"Data Source=WCRDUSMJEMPR9\SQLEXPRESS;Initial Catalog=MicroDB;Integrated Security=True"
Or escape the slash "Data Source=WCRDUSMJEMPR9\\SQLEXPRESS;Initial Catalog=MicroDB;Integrated Security=True"
Related
I have successfully managed to use SELECT and DELETE SQL statements and now I am trying to use INSERT INTO. However I keep getting this error:
ExecuteNonQuery requires an open and available Connection. The
connection's current state is closed.
So I tried putting con.Open() to see if that would help and I got this error:
The ConnectionString property has not been initialized.
I was wondering if anyone knows what I have done wrong. Or just if anyone has any working code. Preferably I would like to not use parameters if that is possible because I don't understand them at all. Here is my SQL code:
Dim con As OleDb.OleDbConnection
Dim comm As OleDb.OleDbCommand
con = SQLConnect()
comm = New OleDb.OleDbCommand()
comm.CommandText = "INSERT INTO " & TableName & " (" & Column & ") VALUES (" & Value & ")"
comm.Connection = con
comm.ExecuteNonQuery()
con.Close()
Here is the connection code:
Public Function SQLConnect() As OleDb.OleDbConnection
If Connector.State = ConnectionState.Open Then
dbprovider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbsource = "Data Source = NEA.accdb"
Connector.ConnectionString = dbprovider & dbsource
Connector.Open()
End If
Return Connector
End Function
Use one open connection and one close connection like this:
Open the connection
Execute all your DELETE and INSERT queries.
Close the connection.
Try this:
con.Open()
comm.Connection = con
comm.CommandText = "DELETE ..."
comm.ExecuteNonQuery()
comm.CommandText = "INSERT INTO " & TableName & " (" & Column & ") VALUES (" & Value & ")"
comm.ExecuteNonQuery()
con.Close()
BTW, I recommend that you use parameters instead of string concatenation on your sql query. To avoid sql injection.
Here is the code I am using :
Try
Dim SqlQuery As String = "DELETE FROM tblEXcel WHERE ID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record deleted..")
Catch ex As Exception
MsgBox(ex.Message, vbOKOnly, "Clear Measurement Table!")
End Try
For DataBindings you can use this...
Do While ExampleBindingSource.Count > 0
ExampleBindingSource.RemoveCurrent()
Loop
Remove WHERE ID = " & id. Then ALL the rows will be deleted.
So, simply change your SQL command to:
Dim SqlQuery As String = "DELETE FROM tblEXcel"
use below statement:
delete * from tblName
Dim SqlQuery As String = "DELETE * FROM tblEXcel WHERE ID = " & id & ";"
Dim MySQLCON As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=test;User ID=root;Password=mysql;")
Dim COMMAND As MySqlCommand
MySQLCON.Open() /Open your Connection
Dim DELETERECORD As String = "DELETE * FROM tblEXcel WHERE ID= #id"
COMMAND = New MySqlCommand(DELETERECORD, MySQLCON)
COMMAND.Parameters.AddWithValue("#id", userID.Text) /userID.Text is the string of the users ID
COMMAND.ExecuteNonQuery()
MySQLCON.Close() /Always Close your Connection
MySQLCON.Dispose() /Always Dispose of your Connection
Note:
The way you where doing it was vulnerable to MySQL Injection Attacks. If you have a lot of MySQL Code in your application, i advise you to rewrite it in the way so it is not vulnerable.
I am connecting to the MS Access server with the following code.
Dim cnn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=162.222.225.78;Database=CRM.mdb;Integrated Security=SSPI;User ID=corpopef;Password=********;")
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO Addressbook(srno) " & _
"VALUES('" & Me.TextBox1.Text & "')"
cmd.ExecuteNonQuery()
But it results in the following error:
"Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done."
Please suggest to me some methods to work around this problem.
Thanks in advance...!
The connection string you used seems like an SQL client connection string. For an access database, you should use this format:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path_to_mdb_file\CRM.MDB;User Id=user_id; Password=password;
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.
I'm using Visual Basic 2010 Express and Access 2003.
I'm trying to make sql querys to the mdb file. I'm using OLEDBConnection. The Select query works fine, but I can't insert rows in the table. Here is the code.
Dim connStr As String = "provider=Microsoft.Jet.OLEDB.4.0;data source=" & System.IO.Directory.GetCurrentDirectory() & "\tpv.mdb;"
Dim con As New OleDb.OleDbConnection(connStr)
con.Open()
Dim query As String = "select * from Productos"
Dim cmd As New OleDb.OleDbCommand(query, con)
Dim reader As OleDb.OleDbDataReader
reader = cmd.ExecuteReader
While reader.Read()
MsgBox(reader.GetValue(0) & ", " & reader.GetValue(1) & " , " & reader.GetValue(2))
End While
reader.Close()
query = "insert into Productos (NombreProducto,PrecioCoste) VALUES ('cana',4)"
Dim cmd2 As New OleDb.OleDbCommand(query, con)
cmd.ExecuteNonQuery()
con.Close()
Why the INSERT query does not work?
Ok, I found my stupid problem.
Althoug I have declared 2 OleDbCommands, I referenced the first one in both cases