I have two function: - Public Sub AddData()
-
Dim sSQL As String = ""
-
Dim check As Boolean = Me.TestExistingRow("QUESTIONARIO1")
-
If check = False Then
-
sSQL = "INSERT INTO QUESTIONARIO1([USER]) VALUES ('" &
-
Me.IdUser & "');"
-
ExecuteNonQuery(Me.ConnString, CommandType.Text, sSQL)
-
End If
-
End Sub
-
-
Public Function TestExistingRow(ByVal NameTable As String) As Boolean
-
Dim sSQL As String = ""
-
Dim n As Integer = 0
-
Dim check As Boolean = True 'la riga esiste
-
sSQL = "SELECT Count([USER]) as tot FROM " & NomeTabella & " where [USER]='" & Me.IdUser & "';"
-
Try
-
n = CInt(ExecuteScalar(Me.ConnString, CommandType.Text, sSQL))
-
If n = 0 Then
-
check = False
-
End If
-
Catch ex As Exception
-
check = True
-
End Try
-
Return check
-
End Function
-
The two function are in a Class named Pippo with this Inizializing New Function: - Public Sub New(ByVal p As Page, ByVal c As HttpContext)
-
SyncLock (Me)
-
Me.IdUser = "VOID"
-
If Not p.Request.Params("IdUser") Is Nothing Then Me.IdUser = p.Request.Params("IdUser").ToString
-
If ((Not c.User Is Nothing) And (Me.IdUser = "VOID" Or Me.IdUser = "")) Then Me.IdUser = HttpContext.Current.User.Identity.Name
-
If Me.IdUser = "" Then Me.IdUser = "VOID"
-
Me.ConnString = Me.GetCN()
-
End SyncLock
-
End Sub
-
Sometimes, a user connect to my application and get this error (that I receive in my mail): Violation of PRIMARY KEY constraint 'PK__QUESTION__ AA65E05E1881A0D E'. Cannot insert duplicate key in object 'dbo.QUESTIONAR IO1'.
The statement has been terminated.
[...]
AUTH_TYPE = Forms
AUTH_USER = BL0210
AUTH_PASSWORD =
LOGON_USER =
REMOTE_USER = BL0210
Etc.
I'm not figuring why this error occures and why it occures only sometimes...
Thank you for your help
13 10644 Rabbit 12,516
Recognized Expert Moderator MVP
You put a primary key constraint on the field USER for the table QUESTIONARIO1. You can't have duplicate values on a primary key. If you need to have duplicates, then you have to remove the primary key.
Yes, of course. But I test if the key i want to insert is unique with the function TestExistingRow - as you can see - and it returns to me false, even if then the application gets the error. This situation occures only sometimes, not always.
The function TestExistingRow counts how many records are existing in the same table with the key that i want to insert and return FALSE ONLY if the numer of row is 0 (zero). The "AddData" function then tries to insert the key ONLY IF the first one (TestExistingRo w) return false. So...why sometimes it return false but then i get the "VIOLATION OF PRIMARY KEY" error?
However, Thanks for your attention! :)
Rabbit 12,516
Recognized Expert Moderator MVP
Have you checked the table itself? You should have it print out the SQL insert command and check the table itself. What is the definition of the primary key on that table? Is it a compound key?
Yes I check the table QUESTIONARI1 with the sql statement "SELECT Count([USER]) as tot FROM " & NomeTabella & " where [USER]='" & Me.IdUser & "';" where NomeTabella is passed to the function as QUESTIONARI1
(have you seen my code above? PLEASE take a look at my code above. There are three function AddData, TestExistingRow and Sub New of the class that calls the two function)
Then I try to insert the same user only if tot=0:
n = CInt(ExecuteSca lar(Me.ConnStri ng, CommandType.Tex t, sSQL))
If n = 0 Then
check = False
End If
If check = False Then
sSQL = "INSERT INTO QUESTIONARIO1([USER]) VALUES ('" &
Me.IdUser & "');"
The table Questionari1 is defined as:
CREATE TABLE [dbo].[QUESTIONARIO1](
[USER] [nvarchar](50) NOT NULL,
[SITO] [nvarchar](max) NULL,
[TELEFONO1] [nvarchar](max) NULL,
CONSTRAINT [PK_QUESTIONARIO 1] PRIMARY KEY CLUSTERED
(
[USER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORE COMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCK S = ON) ON [PRIMARY]
) ON [PRIMARY]
My doubt is that in some cases Me.User is not the same in both function, even if in local test all works fine...
Me.User is the Context.User.Id entity.Name (as you can see in my code above)
Rabbit 12,516
Recognized Expert Moderator MVP
I wasn't asking you if the code is checking for duplicates. I was saying that you should check the table manually. By which I mean, on an error, print out the SQL string and then go to the SQL Server Management Studio and check the table itself.
What do yout mean by "Me.User is not the same in both function"? They need to be the same. What's the point of checking for a duplicate of a record if it's not the name you're trying to insert?
For example: I tried to put a try catch in the functions above and in case of error I send an email to my mailaddress. This was the result:
"The value of TestExistingRow is: False.
The istruction for verifying this was: SELECT Count([USER]) as tot FROM QUESTIONARIO1 where [USER]='MIW0230'.
I tried to run the istruction: INSERT INTO QUESTIONARIO1 ([USER]) VALUES ('MIW0230');"
So the function TestExistingRow returned False (this means that "SELECT Count([USER]) as tot FROM QUESTIONARIO1 where [USER]='MIW0230'" has return tot=0)
But the code has tried however to run the insert statement.....w hy????
I can't figured out why....
If I try the code in local and try to enter the application as MIW0230 (the user that then results in Me.User), I get no error!!!!
Me.User (=Context.User. Identity.Name in Public Sub New) can change during the code if many users enter the application? Because if yes, this is the only answer that I can think.
My pages are asynchron. Can this fact causes some delay and so the error? Mahhhhh???Bohh
Please, help me. This issue is a mistery for me by several days. Thank you
I'm not sure I understand your requirement or perhaps your reason for distributing so much of your logic into many,separate ad-hoc SQL queries.
The easiest solution is to wrap the good ol' TRY...CATCH block in a single stored procedure. eg: -
CREATE PROCEDURE sp_addIfNew(@userVar VARCHAR(32))
-
AS
-
BEGIN
-
BEGIN TRY
-
INSERT INTO QUESTIONARIO1([USER]) VALUES (@userVar)
-
END TRY
-
BEGIN CATCH
-
SELECT
-
ERROR_NUMBER() AS ErrorNumber
-
,ERROR_SEVERITY() AS ErrorSeverity
-
,ERROR_STATE() AS ErrorState
-
,ERROR_PROCEDURE() AS ErrorProcedure
-
,ERROR_LINE() AS ErrorLine
-
,ERROR_MESSAGE() AS ErrorMessage;
-
END CATCH
-
END
-
The SELECT code in the CATCH...END CATCH section should be removed in favor of your on error-handling SP's.
You don't need to iterate(count) all your users to determine whether or not you can insert a row. With TRY/CATCH you just try the insert and respond to the errors(if any) in the CATCH. TRY..CATCH
I'm required by law to discourage you from using ad-hoc queries in your code. especially around login/authentication related tables. This only encourages SQL injection attacks. Using SP's is always preferred.
Just thinking out loud here, SQL is so good at comparing, filtering, combining, and checking existence of it's data, it would be a waste to burden your application with data manipulation tasks better left inside SQL. I always try interface my UI applications to my databases through stored procedures written on SCHEMAs separate from the tables the data is actually stored in. This lets me write the UI language independent because my data logic isn't tangled in the UI code. Also the separate SCHEMA thing supports security because the SQL account that the UI uses wouldn't have rights on the tables if the database ever got injected with malicious code through the UI.
Hello (again) Bytes!
long time no see.
Thanks for the lesson. I also often prefer Stored Procedure, but in this case I need a rude sql statement because I use this function for many cases and i need to parametrize it a lot.
By the way, It's interesting how you catch the error in the SP. But I would prefer to understand why the error occures, instead of avoid it. This is because I want to be sure that the error couldn't be the symptom of a most tragical error in my application.
However I tried to change the sql statement as this:
"IF NOT EXISTS (SELECT 1 FROM QUESTIONARIO1 WHERE [USER] = '" & Me.IdUser & "') INSERT INTO QUESTIONARIO1 ([USER]) VALUES ('" & Me.IdUser & "')"
This statement return to me an error (I sent the error, occured by an user, in my mail) of VIOLATION OF PRIMARY KEY. I just can't figure out why...
I got an error in this moment in my mail address:
"Statement was: IF NOT EXISTS (SELECT 1 FROM QUESTIONARIO1 WHERE [USER] = 'UD06835') INSERT INTO QUESTIONARIO1 ([USER]) VALUES ('UD06835')
Violation of PRIMARY KEY constraint 'PK__QUESTION__ AA65E05E412EB0B 6'. Cannot insert duplicate key in object 'dbo.QUESTIONAR IO1'. The statement has been terminated."
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Prince Kumar |
last post by:
Is there any way I can define an Unique constraint or unique index
which allows more than one null values for the same column combination
in DB2?
ie, If my index is defined on (col3, col4) where both columns allow
nulls, I want col3 + col4 to be unique, if one or both the columns
have values. If both columns have nulls, it should allow more than one
such rows.
ex,
|
by: David Garamond |
last post by:
postgresql 7.4.0, redhat 7.3 (under vmware 4.0 on win2k)
Windows crashed and some of the files on Redhat got corrupted, including
some files in /var/lib/pgsql/data/pg_xlog/. When I tried to start
postmaster, it fails with message "Invalid primary checkPoint record". I
think it was trying to look for files named "0000000000000021" but only
files named "0000000000000022" through "0000000000000027" were there. So
I ran pg_resetxlog (this is...
|
by: Mike Hunter |
last post by:
(Please CC me on any replies as I'm not on the list)
Hi,
After a recent power failure, a program that uses a pgsql backend
(netdisco) started to send me nastygrams. I tried the author's suggestion
of running a VACUUM FULL ANALYZE VERBOSE;, but it still sends me the
messages. The data in the database isn't too important, i.e. I'm willing
to blow away data to try to fix the problem. Any suggestions?
|
by: borajetta |
last post by:
ERROR: duplicate key violates unique constraint "pg_class_oid_index"
I found a post earlier but wanted to post up my info as the other persons did not look like the same type of error:
I tried to cluster the isbn_table
cluster isbn_index_code on isbn_table;
ERROR: duplicate key violates unique constraint "pg_class_oid_index"
The table looks like this
|
by: andro |
last post by:
Hi everybody!
I have several tables from which I want to exract the SAME value (along with
other referenced data).
All the values are in the same column within the tables.
How can I achieve this?
TIA.
Andro
| |
by: embarkr |
last post by:
I am getting the error:
"Violation of PRIMARY KEY constraint 'PK_tblCustomsTariffTreeMap'. Cannot insert duplicate key in object 'dbo.tblCustomsTariffCodeTreeMap'."
However, the record I am inserting does not represent a duplicate on the primary key.
To ensure this I ran the following and still got the error:
update tblCustomsTariffCodeTreeMap
set TariffCodeID = (SELECT max(tariffcodeid)+1 from tblCustomsTariffCodeTreeMap)
where...
|
by: Pietro Cerutti |
last post by:
Dear all,
Consider:
include <stdio.h>
int main(void)
{
printf("%d%d%d");
return (0);
}
|
by: Good Guy |
last post by:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Customers_Contact".
The conflict occurred in database "BreakAway", table "dbo.Contact", column 'ContactID'.
The statement has been terminated.
Hi, all. This is my maiden post.
Some background:
I am doing a C# project using Entity Framework 4.0 in Visual Studio 2010 and SQL Server 2005 Expresss.
The project is from the book, Programming Entity Framework, Chapter 9, which...
|
by: dowlingm815 |
last post by:
I am attempting to create a table with an index. however, i am receiving an error code "3371: Cannot find table or constraint" as soon as it reads the "create index" statement. The code is as follows"
thank you in advance for any guidance.
strSeqNumber_TEMP = " "
strIndexOrg_TEMP = "0"
strFund_TEMP = " "
strAccountCode_TEMP = "0"
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |