Option Value Changed - ODBC Error 2169 - odbc

Thank you for your response.
I am using Powerbasic (www.powerbasic.com) as my compiler and SQLTools as a third party tool to access ADS through ODBC.
I must stat that this error also appers when I take other actions like Update, Delete, Find, etc. But I don't
get this error when I am using MS Access.
Here is my save routine:
Local sUsername As String
Local sPassword As String
Local sStatus As String
Local sSQLStatement1 As String
sUsername = VD_GetText (nCbHndl, %ID_FRMUPDATEUSERS_TXTUSERNAME)
If Trim$(sUsername) = "" Then
MsgBox "Please, enter Username", %MB_ICONINFORMATION Or %MB_TASKMODAL, VD_App.Title
Control Set Focus nCbHndl, %ID_FRMUPDATEUSERS_TXTUSERNAME
Exit Function
End If
sPassword = VD_GetText (nCbHndl, %ID_FRMUPDATEUSERS_TXTPASSWORD)
If Trim$(sPassword) = "" Then
MsgBox "Please, enter Password", %MB_ICONINFORMATION Or %MB_TASKMODAL, VD_App.Title
Control Set Focus nCbHndl, %ID_FRMUPDATEUSERS_TXTPASSWORD
Exit Function
End If
sStatus = VD_GetText (nCbHndl, %ID_FRMUPDATEUSERS_CBOSTATUS)
sSQLStatement1 = "INSERT INTO [tblUsers] (Username, Password, Status) " + _
"VALUES ('" + sUsername + "','" + sPassword + "','" + sStatus +"')"
'Submit the SQL Statement to the database
SQL_Stmt %SQL_STMT_IMMEDIATE, sSQLStatement1
'Check for errors
If SQL_ErrorPending Then
SQL_MsgBox SQL_ErrorQuickAll, %MSGBOX_OK
End If
Best regards,

I am not familiar with Powerbasic and have had trouble attempting to find a trial version. However, I have been thinking about this. You noted that the issue occurs with update and delete as well as this insert statement. This leads me to believe that perhaps an attribute is being set to indicate the statement should return a cursor when it does not. However this is more of a wild guess.
Does an ODBC trace shed any light as to the options that were changed?

Related

how to update entry in mysql table from asp.net?

In mysql workbench, I can type
UPDATE contact_log
SET note = 'test1'
WHERE customer = 'customer'
and it will update the customer's note.
WHen i try this in asp.net, it has no effect.
Try
conn.Open()
cmd.Connection = conn
Catch ex As Exception
End Try
cmd.CommandText = "UPDATE contact_log " +
"SET note = '" & TextBox2.Text & "'" +
"WHERE customer = '" & Request.QueryString("ID") & "'"
reader = cmd.ExecuteReader()
conn.Close()
conn.Dispose()
Some facts are that the connection string is correct, I can use select and bring back data with no problem, and the request.querystring("ID") brings back the customer name.
Is there a better way to update a mysql table from asp.net, or a way that actually works?
Many problems in your code.
Do not use string concatenation to build sql commands, but
parameterized query
Do not catch exceptions and swallow them
Use the appropriate using statement to close and dispose the
connection
Of course an INSERT/UPDATE/DELETE statement requires ExecuteNonQuery
To summarize I would change your code to this
Dim cmdText = "UPDATE contact_log SET note = #note WHERE customer = #cust"
Using conn = new MySqlConnection(connString)
Using cmd = new MySqlCommand(cmdText, conn)
conn.Open()
cmd.Parameters.AddWithValue("#note",TextBox2.Text)
cmd.Parameters.AddWithValue("#cust",Request.QueryString("ID"))
Dim rowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
Parameterized query are very important because you avoid Sql Injections and parsing problems with string containing quotes (You will get a syntax error if the TextBox2 contains a text with a single quote)
The Using Statement will ensure that youR connection is properly closed and disposed also in case of exceptions and you avoid dangerous memory leaks and get lower usage of system resources
The exception is better handled on a upper level of your code where you could show a message to your user or write in an error log. Catching an exception and doing nothing is very bad because you will never learn what is the reason of failure in your code.
You're using the wrong command... You're WRITING to the database, not reading from it - You need to change from using a reader to an execution command....
Try this:
cmd.CommandText = "UPDATE contact_log " +
"SET note = '" & TextBox2.Text & "'" +
"WHERE customer = '" & Request.QueryString("ID") & "'"
cmd.ExecuteNonQuery()
conn.Close()
conn.Dispose()

second ExecuteReader() doesn't work

I have a code which checks the validity of user and then, if a user is valid it inserts certain values in the database.
My problem is when After I query my database to check if a user is valid and after that i try to pass the additional value to its account the flow stops when I invoke ExecuteReader() for the second time.
There is no error, or anything like that. I tried to substitute ExecuteReader() with ExecuteNoneQuery but still it's not working. I tried all the query in mysql command prompt they are working perfectly. I really can't understand what am I doing wrong there. Can anyone help me please?
Here is the code:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE SE_ID = " & Id.Text
Dim smd = New MySqlCommand(stquery, myconn)
Dim myreader = smd.ExecuteReader()
If Not myreader.HasRows Then
errorUser.Visible = True
Else
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
Dim Myreader2 As MySqlDataReader
'smd.ExecuteNonQuery()'
'THE CODE STOPS HERE'
Myreader2 = smd2.ExecuteReader()
'Myreader2.Read()'
MsgBox("The BACKUP INFORMATION HAS BEEN SAVED")
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
Because your second query is an update, not a select, you need to execute it using the ExecuteNonQuery method. Your commented-out code shows an attempt to call ExecuteNonQuery but on the wrong command object (smd when it should be smd2). Try something like this instead:
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd2.ExecuteNonQuery()
The ExecuteNonQuery method returns the number of rows updated as an int value, so you can capture it if it's valuable to you. In your case it's probably not, but here's how you'd check anyway:
int rowsAdded = smd2.ExecuteNonQuery();
if (rowsAdded == 1) {
// expected this
} else {
// didn't expect this
}
Finally, concatenating strings to build SQL commands can leave you vulnerable to SQL Injection attacks. Please take a look at using parameterized queries. There's a decent example here.
If you want to execute nested Reader, you have to create another connection. You need somethig like
smd2 = New MySqlCommand(stquery2, myconn2)' myconn2 is another connection
OR
Set "MultipleActiveResultSets=True in your connection string.
Also, use ExecuteNonQuery() for Inserting
Dim name As String = myreader("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES ('" & name & "', '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd.ExecuteNonQuery()
Please use Parameterized query to avoid SQL Injection
The logic is that you need to close your first reader (myreader) before executing another reader (MyReader2) on the same connection.

Classic ASP Error: Operation is not allowed when the object is closed

I have cruised and implemented code from some of the other responses to this question, but I'm still having no luck. I am still getting the error.
If ((bReport And bIsDate And CheckPermissions("lotsales")) Or Request.QueryString("report")) Then
OpenDB
Dim oRs, sSQL, sSQL2, iCancellations, iSales, sDate, sInitDate, sEndDate, iPhaseID, iPhaseNumber, rowCount
sInitDate = Request("startDate")
sEndDate = Request("endDate")
sSQL = "sp_get_lot_sales_test '" & sInitDate & "', '" & sEndDate & "', " & sPhase & ", '" & sReportView & "'"
'response.write vbNewLine & "<!-- sql: " & sSQL & "-->" & vbNewLine
'response.write sSQL
'response.Flush
Set oRs = ExecuteCommand(sSQL,1)
End If
And then here is where the error occurs -
If (oRs.EOF) Then <-- fails here
Response.Write("<TR><TD ALIGN=""center"">There is no data to report on!</TD></TR>")
Else
Do While Not oRs.EOF
As a last resort I am going to go back to the stored procedure and deconstruct it to make sure all is well there. Does anyone have any insight as to why I might be getting the error? I am not issuing a close anywhere.
Here is the ExecuteCommand function -
Function ExecuteCommand(s,i)
On Error Resume Next
Set ExecuteCommand = oDBc.Execute(s, , i)
End Function
This may be old, but I frequently come across that error (operation is not allowed when object is closed).
What I do is in the stored procedure, I add the follwing:
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
right below the AS in the procedure.
That's all I do and the problem goes away.
I am maintaining some old Classic ASP code for a client, code that we took over from a prior developer, and this bug drove me crazy for 4 hours.
I finally discovered a few PRINT statements in the associated SQL stored procedure, which were there for troubleshooting or checking values but don't actually return rows, yet they caused this to fail:
Set cnContentDB = Server.CreateObject("ADODB.Connection")
cnContentDB2.Open sString
sSQL = "EXEC YourStoredProc"
Set oRS2 = Server.CreateObject("ADODB.Recordset")
oRS2.Open sSQL, cnContentDB
if not oR2.EOF then 'THIS WAS GIVING THE ERROR,
'EVEN THOUGH THE STORED PROC ALWAYS RETURNS RECORDS
I removed the Print statements, and the error went away.
Although this is years old, we still end up here looking for solutions.
The cause of this error for me was that the User did not have Execute permission on the Stored Procedure. Granting Execute permission resolved the error.
You need a connection object.
set conn = server.CreateObject("adodb.connection")
set oRs = conn.execute(sSql)

Issue with ODBC.Net connection to MySQL DB

I'm thinking the problem here is with my SQL Syntax, but I'm not sure and need a fresh pair of eyes to check it out. This is the code I'm using to connect to and then insert into the DB:
OdbcConnection datConn = CreateDataConn();
datConn.Open();
OdbcCommand comm = new OdbcCommand();
comm.CommandText = "INSERT INTO userdata (key, secretkey, uid) VALUES ('" + token + "', '" + secret + "', '" + twitterid + "');";
comm.Connection = datConn;
comm.ExecuteNonQuery();
datConn.Close();
And here is the CreatDataConn() method:
private OdbcConnection CreateDataConn()
{
OdbcConnection dbConn = new OdbcConnection();
dbConn.ConnectionString = "Dsn=MySQL;database=twittertest;option=0;port=0;server=localhost;uid=root;pass=Red!4jedi";
return dbConn;
}
I created a DSN to the database, which is hosted on my machine.
When I run the application I get this error:
ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.51-community]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key, secretkey, uid) VALUES ('127090765-i3aZl71LPSVUCPZs9kHSYeBli0vWpbq0BaM1roYC' at line 1
But for the life of me I can't figure out what's wrong with my syntax...It's prolly something simple, but again, I need a pair of fresh eyes to look at this.
key is a probably a reserved word. in MySQL, you can get around this by adding backticks (`) around a column name (so '`key`'instead of 'key'), but you should try not to have reserved words as entity names.

How to view the last ran sql query from SqlClient data provider on Sql server 2000?

Although I have been able to see the last ran query which is a Stored Procedure executed but I didn't get the parameters values with which the SP was invoked. Rather I got the following:
StoredProcedureName;1
from the following command:
DBCC INPUTBUFFER(SPID)
Where I got the SPID by viewing it in the ObjectExplorer->Management->ActivityMonitor
Is there any way I can get the complete text including the parameters with which the SP was executed ?
I know this answer may not be what you are looking for, as it doesn't really answer your question, I took a leap of thought and ended up thinking this might help.
I don't know how many queries you have and how big your program is... but for debugging purposes I wanted to do something similar for all of my queries, both plain text and stored procedures. So I wrote a simple wrapper class that lets me execute plain text queries/stored procs with and without parameters. Then, if an execption occurs, I trap it, build a new custom exception with the original exception plus the query that was executed and all parameters, and return it all in a custom message. I'm using Oracle in my wrapper but it's almost exactly the same:
Public Function ExecuteCommandQuery(ByRef oCMD As OracleClient.OracleCommand) As DataTable
oCMD.Connection = _oConn
Dim dt As New DataTable
'exception if one occured'
Dim DBException As Exception = Nothing
Try
'get an adapter'
Dim cmd As New OracleDataAdapter(oCMD)
'Fill the data table and ket a count of records returned'
cmd.Fill(dt)
Catch ex As Exception
'capture exception, and rethrow after properly closing the Oracle Connection'
DBException = ex
Finally
_oConn.Close()
End Try
'if exception occured, rethrow'
If DBException IsNot Nothing Then
Throw New Exception( _
String.Format("A database error occured: {0} " + _
Environment.NewLine + Environment.NewLine + " --- " + _
Environment.NewLine + Environment.NewLine + _
" Your query: {1}" + _
Environment.NewLine + Environment.NewLine + " --- " + _
Environment.NewLine + Environment.NewLine + _
" Your Parameters: " + Environment.NewLine + "{2}" _
, DBException.ToString(), oCMD.CommandText, GenerateParameterErrorInfo(oCMD)))
End If
Return dt
End Function

Resources