I have PreparedStatement(ps) below, populate it as shown and when executed MSSQL errors as shown last below. Of course there is NO value of "TRADEIN" in any data that can be seen. Ideas?
String update = "UPDATE IM_ITEM SET "
+ "LST_COST=?, PRC_1=?, IS_TXBL=?, TAX_CATEG_COD=?,CATEG_COD=?"
+ " WHERE ITEM_NO="+itemNo;
populate:
ps.setString(++i, q.get("LST_COST"));
ps.setString(++i, q.get("PRC_1"));
ps.setString(++i, q.get("IS_TXBL"));
ps.setString(++i, q.get("TAX_CATEG_COD"));
ps.setString(++i, q.get("CATEG_COD"));
debugged: "sqlCommand" and "userSQL" are still parameterized only
UPDATE IM_ITEM SET LST_COST=?, PRC_1=?, IS_TXBL=?, TAX_CATEG_COD=?, CATEG_COD=? WHERE ITEM_NO=101316
error:
Severe: com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the varchar value 'TRADEIN' to data type int.
Answered, kindly, by Seanlange in the chat.
Related
I am calling a karate DButil to execute one of the database query in the karate script:
* def test = db.readValue('SELECT * FROM CLIENT C WHERE C.ClientCode = ' + globalAccountID)
Here i', unable to convert the globalAccountID to string.
Please help on this.
My error trace is below:
javascript evaluation failed: db.readRows('SELECT * FROM CLIENT C
WHERE C.ClientCode = ' + globalAccountID), StatementCallback;
uncategorized SQLException for SQL [SELECT * FROM CLIENT C WHERE
C.ClientCode = 707]; SQL state [S0001]; error code [245]; Conversion
failed when converting the varchar value 'YTLQVLBK' to data type int.;
nested exception is com.microsoft.sqlserver.jdbc.SQLServerException:
Conversion failed when converting the varchar value 'YTLQVLBK' to data
type int.
The issue is in this code:
C.ClientCode = 707
More specifically, you are comparing an integer to a string. Based on SQL Server Data type precedence rules, it means that column C.ClientCode is converted to integer before comparison can take place.
The solution is to convert 707 to string (varchar) type. You can do something like this:
'SELECT * FROM CLIENT C WHERE C.ClientCode = ''' + globalAccountID + ''''
Below is my code for adding parameters in my vb .net code for prepared statements of Npgsql:
Dim xConn As NpgsqlConnection = ConnectDB()
Dim xCmd As NpgsqlCommand = xConn.CreateCommand()
xCmd.CommandText = "UPDATE " & xTable & " SET previous_tot_adj = #prev_adj ,tot_adj = #tot_adj WHERE version = " & _version & " AND monthly_mq_id = #Index"
For Each Index In _Results.Keys
If Not IsNothing(_Results.Item(Index)) Then
xCmd.Parameters.AddWithValue("prev_adj", NpgsqlTypes.NpgsqlDbType.Double, _Results.Item(Index))
xCmd.Parameters.AddWithValue("tot_adj", NpgsqlTypes.NpgsqlDbType.Double, _Results.Item(Index))
xCmd.Parameters.AddWithValue("Index", NpgsqlTypes.NpgsqlDbType.Bigint, Index)
End If
Next
xCmd.Prepare()
xCmd.ExecuteNonQuery()
After executing this code, I get this kind of error:
A first chance exception of type 'Npgsql.NpgsqlException' occurred in Npgsql.dll
ERROR: 08P01: bind message has 34193 parameter formats but 1 parameters
Can anyone enlighten me for what's wrong on what I'm doing?
Ifound out the problem,i was using an outdated Npgsql. I jus installed the new verion v4.0.1 NugetGallery. This fixed the issue.
I'm trying to write code to insert new items into a database.
if(isset($_POST['btnAddVeg'])){
$addVegType = $_POST['txtAddVegType'];
$AddVegName = $_POST['txtAddVegName'];
$insertQuery = 'insert into vegetables (vegetable_type, vegetable_id) values ("$addVegType", "$AddVegName")';
$statement2 = $db->prepare($insertQuery);
$statement2->execute();
$results2 = $statement2->fetchAll();
$statement2->closeCursor();
foreach($results2 as $result2){
echo "<table border = '0'><th>ID</th><th>Type</th><th>Name</th> <tr><td>".$result2['vegetable_id'].'</td>';
echo "<td>".$result2['vegetable_type'].'</td>';
echo "<td>".$result2['vegetable_name'].'</td></tr></table>';
}
I get this error:
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error in /vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/task9.php(54): PDOStatement->fetchAll() #1 {main} thrown in vvvvvvvvvvv/task9.php on line 54
Probably ridiculously easy but what am I missing?
Thank you
Executing an INSERT statement doesn't return a resultset object.
Just remove the line that does the statement2->fetchAll.
And remove the lines that reference $results2.
We would need that if we were executing a SELECT statement, to get a resultset (a set of rows) returned.
Also important to point out: the code is vulnerable to SQL Injection.
https://xkcd.com/327/
https://www.owasp.org/index.php/SQL_Injection
I am trying to use python to insert values into a table.
TableName = "Table_Test1"
This is the code that I am trying:
cursor.execute("Insert into " + TableName + " (TestCol1,TestCol2) VALUES (?,?)", Val1, Val2)
What is the mistake that I am making here?
It is giving me this error - <class 'pyodbc.ProgrammingError'> returned a result with an error set
TestCol2 in the db was declared as nvarchar and the Val2 that the program returned was 0 which is an integer. I changed the datatype in the db and then the program started working.
So this is really weird.
I run a sql command from .net on sqlserver with a 'Select Count(*)' and get a response like "Needs attention CA" (which is in a varchar of one field of one record of the inner joined tables).
Huh? How can Count(*) return a string? 999 out of 1000 times this code executes correctly. Just sometimes on some clients servers it will throw a string of errors for an hour or so only to miraculously stop again.
This is my sqlcommand:
SELECT Count(*)
FROM patientsappointments
INNER JOIN appointmenttypes
ON patientsappointments.appointmenttypeid =
appointmenttypes.appointmenttypeid
WHERE ( ( patientsappointments.date > #WeekStartDate
AND patientsappointments.date < #WeekFinishDate )
AND ( patientsappointments.status = 'Pending' )
AND ( patientsappointments.doctorid = #DoctorID )
AND ( appointmenttypes.appointmentname <> 'Note' ) )
And these are the parameters:
#WeekStartDate = 24/06/2013 12:00:00 AM (DateTime)
#WeekFinishDate = 1/07/2013 12:00:00 AM (DateTime)
#DoctorID = 53630c67-3a5a-406f-901c-dbf6b6d1b20f (UniqueIdentifier)
I do a sqlcmd.executescalar to get the result. Any ideas?
The actual executed code is:
SyncLock lockRefresh
Dim WeekFulfilled, WeekPending As Integer
Using conSLDB As New SqlConnection(modLocalSettings.conSLDBConnectionString)
Dim mySQL As SqlCommand
mySQL = New SqlCommand("SELECT COUNT(*) FROM PatientsAppointments INNER JOIN AppointmentTypes ON PatientsAppointments.AppointmentTypeID = AppointmentTypes.AppointmentTypeID " & _
"WHERE ((PatientsAppointments.Date > #WeekStartDate AND PatientsAppointments.Date < #WeekFinishDate) AND (PatientsAppointments.Status = 'Pending') " & _
"AND (PatientsAppointments.DoctorID = #DoctorID) AND (AppointmentTypes.AppointmentName <> 'Note'))", conSLDB)
Try
mySQL.Parameters.Add("#WeekStartDate", SqlDbType.DateTime).Value = MonthCalendar1.SelectionStart.Date.AddDays(-MonthCalendar1.SelectionStart.Date.DayOfWeek).AddDays(1)
mySQL.Parameters.Add("#WeekFinishDate", SqlDbType.DateTime).Value = MonthCalendar1.SelectionStart.Date.AddDays(-MonthCalendar1.SelectionStart.Date.DayOfWeek).AddDays(8)
mySQL.Parameters.Add("#DoctorID", SqlDbType.UniqueIdentifier).Value = cboDoctors.SelectedValue
conSLDB.Open()
'got errors here like "Conversion from string "R2/3" to type 'Integer' is not valid." Weird.
'failing on deadlock - maybe due to simultaneous updating from udp event. Try adding random delay to refresh
WeekPending = mySQL.ExecuteScalar
Catch ex As Exception
ErrorSender.SendError("frmAppointmentBook - RefreshHeader 1", ex, New String() {String.Format("mySQL.commandtext: {0}", mySQL.CommandText), _
String.Format("mySQL.Parameters: {0}", clsErrorSender.ParamsListToString(mySQL.Parameters))})
End Try
Me.lblPendingWeek.Text = WeekPending
Try
mySQL.CommandText = "SELECT COUNT(*) FROM PatientsAppointments INNER JOIN AppointmentTypes ON PatientsAppointments.AppointmentTypeID = AppointmentTypes.AppointmentTypeID WHERE " & _
"(PatientsAppointments.Date > #WeekStartDate AND PatientsAppointments.Date < #WeekFinishDate) AND (PatientsAppointments.Status = 'Fulfilled') AND " & _
"(PatientsAppointments.DoctorID = #DoctorID) AND (AppointmentTypes.AppointmentName <> 'Note')"
'didn't get the error here... but just in case...
WeekFulfilled = mySQL.ExecuteScalar
Catch ex As Exception
ErrorSender.SendError("frmAppointmentBook - RefreshHeader 2", ex, New String() {String.Format("mySQL.commandtext: {0}", mySQL.CommandText)})
End Try
conSLDB.Close()
End Using
End SyncLock
The exact error message is:
System.InvalidCastException
Conversion from string "Needs Attention DC" to type 'Integer' is not valid.
Your problem has nothing to do with the COUNT(*) portion of your code. The problem is somewhere else in your query. What that particular error is telling you is that at some point you are comparing a character field (it probably usually contains numbers) to an integer field. One of the values of the character field happens to be "Needs Attention DC". If I had to guess it is probably either patientsappointments.appointmenttypeid or appointmenttypes.appointmenttypeid. Double check the datatype of each of those columns to make sure they are in fact INT. If they are both INT then start checking the other explicitly named columns in your query to see if you have any surprises.
You must have an error somewhere in your implementation...
Per the documentation, count always returns an int data type value.
Since this doesn't always happen, it must be a result of one of the paramenter values that is sent in. This is one of the lbuiggest problems with using dynamic SQL. What I would do is create the dymanic SQl and then store it in a database logging table with the date and time and user who executed it. Then when you get the exception, you can find the exact SQL code that was sent. Most likely you need more controls on the input variables to ensure the data placed in them is of the correct data type.
I am going to make another guess. I am guessing that this is a multi threading issue. You probably are sharing the connection between multiple threads. Once in a while the thread will get that man from somewhere else and execute it. Make sure that the connection variable is local, and only one thread can access it at a time.
As Martin points out, the following answer is wrong. I'm keeping this here to show that this is wrong.
From what everyone has already said, there is a type mismatch on your columns. Since your where clause appears to be fine, and your join is fine, it must be elsewhere. I would check to see if patientsappointments or appointmenttypes are views. Maybe the view has a join that's throwing the exception. Check the schema definition of all your joins/where's. Somewhere in there you're storing integers in a character field. It's fine for most rows, but one of them has your string.
If it's not in your views, it may be a trigger somewhere. The point is that somewhere there is a schema mismatch. Once you find your schema mismatch, you can find the row by querying for that string.