String was not recognized as a valid Boolean Error on varchar column - vb.net

I am getting this error:
String was not recognized as a valid Boolean.Couldn't store <No> in meetsstd Column. Expected type is Boolean
When I am running this query:
SELECT * FROM work_nylustis_2013_q3.nylustis_details WHERE siteid = 'NYLUSTIS-155718' LIMIT 50
From this code:
Adapter.SelectCommand = New NpgsqlCommand(SQL, MLConnect)
Adapter.Fill(subDT) ' This line throws error
The meetsstd field is a varchar(3) and it does store either a 'Yes' or a 'No' value. How is this getting this confused with a boolean - a varchar should not care whether is holds 'Yes', or 'Si', or 'Oui'? And it only happens on 27 records out of the 28,000 in the table.
I usually blame npgsql for this kind of strangeness, but the last entry in the stack trace is: System.Data.DataColumn.set_Item(Int32 record, Object value)
Any clues?
Thanks!
Brad

To check if it is problem with database or with driver you can reduce problem to one row and column using your current environment:
SELECT meetsstd FROM work_nylustis_2013_q3.nylustis_details WHERE sitenum=1
(of course you must change sitenum into primary key)
Then try such query using psql, pgAdmin or some JDBC/ODBC based general editor.
If psql shows such record which raises error with your Npgsql based application then problem is with Npgsql driver or problem is with displaying query results.
If other tools shows such strange errors then problem is with your data.
Have you changed type of meetsstd field? Mayby you try to show it on some grid and this grid used Boolean field which was converted to Yes/No for displaying?

Related

npgsql executescalar() allways returns nothing

I'm using npgsql as a nuget package in visual studio 2017 with visual basic.
Various commands do work very well but an ExecuteScalar allways returns 'nothing' although it should give a result.
The command looks like this:
Dim ser As Integer
Dim find = New NpgsqlCommand("SELECT serial from dbo.foreigncode WHERE code = '#code';", conn)
Dim fcode = New NpgsqlParameter("code", NpgsqlTypes.NpgsqlDbType.Varchar)
find.Parameters.Add(fcode)
find.Prepare()
fcode.Value = "XYZ"
ser = find.ExecuteScalar() ==> nothing
When the command string is copied as a value during debugging and pasted into the query tool of PGADMIN it delivers the correct result. The row is definitely there.
Different Commands executed with ExecuteNonQuery() work well, including ones performing UPDATE statements on the row in question.
When I look into the properties of the parameter fcode immediately before the ExecuteScalar it shows 'fcode.DataTypeName' caused an exception 'System.NotImplementedException'.
If I change my prepared statement to "SELECT #code" and set the value of the parameter to an arbitrary value just this value is returned. There is no access to the table taking place because the table name is not part of the SELECT in this case. If I remove the WHERE CLAUSE in the SELECT and just select one column, I would also expect that something has to be returned. But again it is nothing.
Yes there is a column named serial. It is of type bigint and can not contain NULL.
A Query shows that there is no single row that contains NULL in any column.
Latest findings:
I queried a different table where the search column and the result column happen to have the same datatype. It works, so syntax, passing of parameter, prepare etc. seems to work in principal.
The System.NotImplementedException in the DataTypeName property of the parameter occurs as well but it works anyway.
I rebuilt the index of the table in question. No change.
Still: when I copy/paste the CommandText and execute it in PGAdmin it shows the correct result.
Modifying the Command and using plain text there without parameter and without prepare still does yield nothing. The plain text CommandText was copy/pasted from PGAdmin where it was successfully executed before.
Very strange.
Reverting search column and result column also gives nothing as a result.
Please try these two alternatives and post back your results:
' Alternative 1: fetch the entire row, see what's returned
Dim dr = find.ExecuteReader()
While (dr.Read())
Console.Write("{0}\t{1} \n", dr[0], dr[1])
End While
' Alternative 2: Check if "ExecuteScalar()" returns something other than an int
Dim result = find.ExecuteScalar()
... and (I just noticed Honeyboy Wilson's response!) ...
Fix your syntax:
' Try this first: remove the single quotes around "#code"!
Dim find = New NpgsqlCommand("SELECT serial from dbo.foreigncode WHERE code = #code;", conn)
Update 1
Please try this:
Dim find = New NpgsqlCommand("SELECT * from dbo.foreigncode;", conn)
Q: Does this return anything?
Dim dr = find.ExecuteReader()
While (dr.Read())
Console.Write("{0}\t{1} \n", dr[0], dr[1])
End While
Q: Does this?
Dim result = find.ExecuteScalar()
Q: Do you happen to have a column named "serial"? What is it's data type? Is it non-null for the row(s) with 'XYZ'?
Please update your original post with this information.
Update 2
You seem to be doing ":everything right":
You've confirmed that you can connect,
You've confirmed that non-query updates to the same table work (with npgsql),
You've confirmed that the SQL queries themselves are valid (by copying/pasting the same SQL into PGAdmin and getting valid results).
As Shay Rojansky said, "System.NotImplementedException in the DataTypeName property" is a known issue stepping through the debugger. It has nothing to do with your problem: https://github.com/npgsql/npgsql/issues/2520
SUGGESTIONS (I'm grasping at straws)::
Double-check "permissions" on your database and your table.
Consider installing a different version of npgsql.
Be sure your code is detecting any/all error returns and exceptions (it sounds like you're probably already doing this, but it never hurts to ask)
... and ...
Enable verbose logging, both client- and server-side:
https://www.npgsql.org/doc/logging.html
https://www.postgresql.org/docs/9.0/runtime-config-logging.html
... Finally ...
Q: Can you make ANY query, from ANY table, using ANY query method (ExecuteReader(), ExecuteScalar(), ... ANYTHING) from your npgsql/.Net client AT ALL?
I finally found it. It's often the small things that can have a big impact.
When the value was assigned to the parameter a substring index was incorect.
Now it works perfectly.
Thanks to everybody who spent his time on this.

NS_ERROR_FAILURE in SQLite insert

I just bought a Kobo eReader which forces me to register at their website before the eReader functions. Seeing that I'm quite a privacy fundamentalist I refuse to register to read a couple books, so I went searching for an alternative. This brought me to this blogpost, which suggests to open the SQLite DB on the eReader and manually inserting a user with the following insert (formatted for readability):
INSERT INTO user (
UserID
,UserKey
,UserDisplayName
,UserEmail
,___DeviceID
,HasMadePurchase
)
VALUES (
‘5b8b0d65-b50f-4460-b6df-aca5e64f4882’
,’626d73ed-8382-4c1d-9750-cfe741c6e773’
,’a_name’
,’an_email_address’
,’01:23:45:67:89:ab’
,’TRUE’
);
So I found the sqlite database and I ran the query, but I get the following error message
SQLiteManager: Likely SQL syntax error: INSERT INTO user(UserID,UserKey,UserDisplayName,UserEmail,___DeviceID,HasMadePurchase) VALUES(‘5b8b0d65-b50f-4460-b6df-aca5e64f4882’,’626d73ed-8382-4c1d-9750-cfe741c6e773’,’a_name’,’an_email_address’,’01:23:45:67:89:ab’,’TRUE’);
[ unrecognized token: "4c1d" ]
Exception Name: NS_ERROR_FAILURE
Exception Message: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [mozIStorageConnection.createStatement]
I looked at the structure of the user table, which is (as you can see below), slightly different from the the query.
CREATE TABLE user (
UserID TEXT NOT NULL
,UserKey TEXT NOT NULL
,UserDisplayName TEXT
,UserEmail TEXT
,___DeviceID TEXT
,FacebookAuthToken TEXT <= missing from query
,HasMadePurchase BIT DEFAULT FALSE
,IsOneStoreAccount BIT DEFAULT FALSE <= missing from query
,IsChildAccount BIT DEFAULT FALSE <= missing from query
,PRIMARY KEY (UserID)
)
As you can see there are three columns in the db which are not in the query. I don't think that this is the source of the error though.
Does anybody know what the error means and how I can solve the error? All tips are welcome!
Change the single quotes on the VALUES section to double quotes - the error references the middle portion of your string.
In addition to that, surround the column values in backticks and then everything works.

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. error in VB.Net

There were three similar questions in StackOverFlow but none gave an answer..
If have found why this error in occurring but don't know the fix.
I am using Strongly Typed Dataset for my project which is created as a dll for DAL.
I have added the Sql Server Table into this dataset using the designer and has created a DataAdapter
It works fine when i insert using DataTableAdapter
daLabTest.Insert(txtLabTestId.Text, cmbLabTestType.Text, cmbTestName.Text, txtLabFees.Text, dtpLabEffDate.Value)
but when i want to show the data from the table in a combobox or gridview i get this error.
i told that i found out what the problem is, I just previewed the data using DataSet designer and found out that the Function returns data like this...
The query i wrote to view this in dataset is
Select distinct(TestType) from LabTestTypes
so this should return only one column but the dataset is returning 5 columns but others as null, and the TestName column is a primary which should not be null when returned, so the problem exists..
To resolve this i tried to change the NullValue & AllowDBNull property to [Empty] and true respectively but that didn't worked for me.
Please help me in this...
That overly general constraint exception is nasty, where's the InnerException after so many complaints?!
This template may help identify the problem row and column but a "Fill" version of the query function is needed. E.g. GetDistinct*() --> Fill*(). Then a table can be created and interrogated for the row's error text.
SomeTable tTable = new SomeTable()
try {
// sorry, if you have a GetData, change to the fill version
someTable.FillByActiveLogin(tTable, loginName);
} catch (System.Data.ConstraintException constrExc) {
System.Data.DataRow[] rowsErr = tTable.GetErrors();
for (int i = 0; i < rowsErr.Count(); i++)
if (rowsErr[i].HasErrors)
Dbg.WriteLine(rowsErr[i].RowError);
}
(Thanks Michael S for this hint whoever/wherever you are!)
I got this error in a function from a DLL that uses a stored procedure. The procedure did not return all the fields in the table. One of the fields excluded was one that cannot be null. That apparently caused the constraint exception. When I changed the procedure and the DLL to include that field, the exception went away.
After spending ages on this problem myself, I have resolved it modifying the query in the dataset to return a dummy value (that can be ignored) for each key field that is not required in the output.
So your query would become...
Select distinct TestType, 1 as ID, "Dummy" as TestName, "Dummy" as TestFees, "Dummy" as TestDate
from LabTestTypes

How does NHibernate Projections.Max work with an empty table?

I'm trying to get the maximum value of an integer field in a table. Specifically, I'm trying to automatically increment the "InvoiceNumber" field when adding a new invoice. I don't want this to be an autoincrement field in the database, however, since it's controlled by the user -- I'm just trying to take care of the default case. Right now, I'm using
session.CreateCriteria<Invoice>()
.SetProjection(Projections.Max("InvoiceNumber"))
.FutureValue<int>();
to get the biggest invoice number already in the database. This works great, except when there are no invoices already in the database. Then I get a System.ArgumentException: The value "" is not of type "System.Int32" and cannot be used in this generic collection. Changing to FutureValue<int?>() didn't solve the problem. Is there a way to tell NHibernate to map the empty string to null? Or is there a better way to accomplish my goal altogether?
The stack trace of the exception (at least the relevant part) is
NHibernate.HibernateException: Error executing multi criteria : [SELECT max(this_.[InvoiceNumber]) as y0_ FROM dbo.[tblInvoice] this_;
SELECT this_.ID as ID647_0_, this_.[NHVersion] as column2_647_0_, this_.[Description] as column3_647_0_, this_.[DiscountPercent] as column4_647_0_, this_.[DiscountDateDays] as column5_647_0_, this_.[PaymentDueDateDays] as column6_647_0_, this_.[Notes] as column7_647_0_, this_.[DiscountDateMonths] as column8_647_0_, this_.[PaymentDueDateMonths] as column9_647_0_, this_.[DiscountDatePeriod] as column10_647_0_, this_.[DiscountDateMonthlyDay] as column11_647_0_, this_.[DiscountDateMonthlyDayDay] as column12_647_0_, this_.[DiscountDateMonthlyDayMonth] as column13_647_0_, this_.[DiscountDateMonthlyThe] as column14_647_0_, this_.[DiscountDateMonthlyTheDOW] as column15_647_0_, this_.[DiscountDateMonthlyTheMonth] as column16_647_0_, this_.[DiscountDateMonthlyTheWeek] as column17_647_0_, this_.[PaymentDueDatePeriod] as column18_647_0_, this_.[PaymentDueDateMonthlyDay] as column19_647_0_, this_.[PaymentDueDateMonthlyDayDay] as column20_647_0_, this_.[PaymentDueDateMonthlyDayMonth] as column21_647_0_, this_.[PaymentDueDateMonthlyThe] as column22_647_0_, this_.[PaymentDueDateMonthlyTheDOW] as column23_647_0_, this_.[PaymentDueDateMonthlyTheMonth] as column24_647_0_, this_.[PaymentDueDateMonthlyTheWeek] as column25_647_0_ FROM dbo.[tblTermsCode] this_;
] ---> System.ArgumentException: The value "" is not of type "System.Int32" and cannot be used in this generic collection.
Parameter name: value
at System.ThrowHelper.ThrowWrongValueTypeArgumentException(Object value, Type targetType)
at System.Collections.Generic.List`1.VerifyValueType(Object value)
at System.Collections.Generic.List`1.System.Collections.IList.Add(Object item)
at NHibernate.Impl.MultiCriteriaImpl.GetResultsFromDatabase(IList results)
use....UniqueValue<int?>();
NH uses a non-generic IList in their MultiCriteria implementation. Which is used for FutureValue batching. see here for why List<int?> fails to add null through it's IList implementation. I'm surprised I've never run into this before. Avoid using nullable value types with Future or MultiCriteria.
With the QueryOver API:
Session.QueryOver<T>()
.Select(Projections.Max<Statistic>(s => s.PeriodStart))
.SingleOrDefault<object>();
if nothing is returned its null, otherwise cast the result as numeric

CLOB WRITE WITH OO4O

I get the error : OIP-04908: This operation is not permitted on a Null LOB when
Set MyClOB_0 = lOraDynaset_0.Fields("FILE_BODY").Value
lOraDynaset_0.Edit
amount_written = MyClOB_0.Write(buffer, chunksize, ORALOB_FIRST_PIECE)
I've just had the same problem when trying to insert into an Oracle CLOB field.
I got around it by:
Setting the Oracle field to 'Empty' (the VB6 keyword Empty - e.g. MyClOB_0.Value = Empty)
Performing the insert (e.g. lOraDynaset_0.Update)
Editing the dynaset record (e.g. lOraDynaset_0.Edit)
Setting the Clob field value to what you want it
Performing the update (e.g. lOraDynaset_0.Update)
Hope this helps (sorry if its not clear)