update SQL and get error - c#

hi i have many problem with update sql database from c# form
fisrt: i use this code for a button called "Update" that get values directly from text boxes and fill main sql server database.
SqlConnection cnt = new SqlConnection("Data Source=.;Initial Catalog=db3;Integrated Security=True");
SqlCommand cmd = new SqlCommand("update phone set name=#name,lastname=#lastname,Phone=#Phone,Mobile=#Mobile,Area=#Area,date=#date", cnt);
cnt.Open();
cmd.Parameters.AddWithValue("#name", namebox.Text);
cmd.Parameters.AddWithValue("#lastname", lastbox.Text);
cmd.Parameters.AddWithValue("#Phone", phonebox.Text);
cmd.Parameters.AddWithValue("#Mobile", mobilebox.Text);
cmd.Parameters.AddWithValue("#Area", areabox.Text);
cmd.Parameters.AddWithValue("#date", datestring);
cmd.ExecuteNonQuery();
cnt.Close();
but it get error in mobile column :
Violation of UNIQUE KEY constraint 'UQ__phone__5C7E359EA73D3013'. Cannot insert duplicate key in object 'dbo.phone'. The duplicate key value is (4802615).
Note 2: I am using this code for select and view selected row ready for edit
1-Problem Solved the SQL column was Unique index so i removed that.
2- there wasn't a "where condition" so i fixed that too

Where clause is not used so all the rows in the table are getting updated and hence the error is getting generated.

Add a "WHERE Phone=#phone" and it's associated parameter command. As the other person pointed out, you're updating but you haven't told the database to specifically focus on an individual record, so your command updates them all.
This is fine for the first record, as soon as it tries updating the second, it blows up because phone has a unique constraint on it, preventing any other record having the same data. That's your error message.
You need to change your update statement to target the exact record you want to update.

I think you should set the PK or you update all the rows in the phone table.
for example: UPDATE tablename SET columName WHERE ....
I hope this will be useful

Related

Problem with database connection C# from System.Data.SqlClient

I have looked at all the similar questions on this topic but none seem to work for me.
When I try to run my application, I get the following error:
System.Data.SqlClient.SqlException: 'Cannot insert the value NULL into column 'Id', table 'C:\FINALLY\DATABASE.MDF.dbo.loginTB'; column does not allow nulls. INSERT fails.
Here is my code:
private void btnContinued_reg_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\finally\DataBase.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd= new SqlCommand("insert into loginTB(username,password)values('" + txtUserName_reg.Text + "','" + txtPaswword_reg.Text + "')",cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("good");
}
What am I doing wrong?
A snapshot of my code:
The problem does not indicate a connection problem at all. It seems that you are trying to insert a record into a table, and you are trying to pass null as the id, which gives you the error.
My guess would be the error is in the definition of that table loginTB, you make sure the column id has the property IDENTITY, since you are using SQL Server.
An example would be like this:
CREATE TABLE new_employees
(
id_num int PRIMARY KEY IDENTITY(1,1),
fname varchar (20),
minit char(1),
lname varchar(30)
);
Identity columns can be used for generating key values. The identity property on a column guarantees the following:
Each new value is generated based on the current seed & increment.
Each new value for a particular transaction is different from other concurrent transactions on the table.
The identity property on a column does not guarantee the following:
Uniqueness of the value
Uniqueness must be enforced by using a PRIMARY KEY or UNIQUE constraint or UNIQUE index.
Follow up answer of previous answers.
If you already created a table and want to modify it to work correctly:
Go to the table properties from SSMS tool and select the identity column and save the properties. Identity column must be marked as not nullable.

error: "select command that does not return any key", but Im sure that Im giving a key

Im trying update a table, everything works fine with all my tables but with 1 I have this error:
http://i.stack.imgur.com/YQ75B.jpg
(I cant post images sorry)
and it have a primary key
http://i.stack.imgur.com/U9QJL.jpg
the problem must be in this table because everything works well with any other table, I also tried deleting and creating again the primary key column but the error persist,change the column name neither solves it. If I use this query the sql server can find my primary key so it exist:
SELECT
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
but in the update I still receive the same error:
SqlConnection con = new SqlConnection(Conn1.connectionString);
SqlDataAdapter daCust = new SqlDataAdapter("select * from Item", con);
SqlCommandBuilder cbCust = new SqlCommandBuilder(daCust);
daCust.Update(ds.Tables[0]);
(I'm sending "ds" to my webserver from a datagridview with all Item columns so it match)
as I said just the table "Item" cant be updated I tried with tens of other tables without problems, and cant understand what I'm doing wrong

How to insert values into SQL field with a key connection

I've got a table called Devices
Devices has a key field called Names.
As well there are fields; DeviceIP, DoesBackup, DeviceType, and LastBackup
Field LastBackup currently has no knowledge of a devices last backup, the app I am writing will SSH the FTP to find that information.
Now I'm using splits and arrays to break the SSH responses into device name and lastbackup, turning them each into a variable.
Now I need to insert LastBackup into the empty field in my SQL while maintaining pairing to each device based on it's key Name.
I am not sure how to accomplish this as I've read you cannot use a WHERE clause with INSERT.
To insert or update a record (insert if not exists, update if exists) you need a query like this.
First you build the connection object and the command object, then set the commandtext to an sql insert operation with the clause that if the record with the primary key exists (the device name) you want an update instead of an insert.
Finally you add the parameters required by the command (the #xxxx strings) and call ExecuteNonQuery.
using(MySqlConnection cnn = new MySqlConnection(..put a connstring here...))
using(MySqlCommand cmd = cnn.CreateCommand())
{
cnn.Open();
cmd.CommandText = #"INSERT INTO devices
(Names, DeviceIP, DoesBackup, DeviceType, LastBackup)
VALUES (#name, #ip, #backs, #type, #last)
ON DUPLICATE KEY UPDATE LastBackup=#last";
cmd.Parameters.AddWithValue("#name", variableWithDeviceNameValue);
cmd.Parameters.AddWithValue("#ip", variableWithIPValue);
cmd.Parameters.AddWithValue("#backs", variableWithDoesBackupValue);
cmd.Parameters.AddWithValue("#type", variableWithDeviceTypeValue);
cmd.Parameters.AddWithValue("#last", variableWithLastBackupValue);
cmd.ExecuteNonQuery();
}

How to delete a record?

I have records in table1, if the records exist, it must copy into table2. I want to delete those records in a table1 once all the records are copied into another table2. Im still a beginner in database and with some researches, i found some tutorials on d internet how to connect with database, and the codes easy to understand so i came out with this program.This codes only do the copy part and i'm still lack of the delete part. Can help me figure out how to do the delete part? i found 2 reference in msdn, but i'm not sure and not understand on the codes given.
try
{
//create connection
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("Data Source=.dbname;Integrated Security=True;User Instance=True");
//command queries
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO tblSend (ip, msg, date) SELECT ip, msg, date FROM tblOutbox";
cmd.Connection = sqlConnection1;
sqlConnection1.Open(); //open con
cmd.ExecuteNonQuery(); //execute query
sqlConnection1.Close(); //close con
}
catch (System.Exception excep)
{
MessageBox.Show(excep.Message);
}
If i replace the query into this: //cmd.CommandText = "DELETE tblSend WHERE id = 5";
its only delete one rows. But what if many records involved? Do i need to consider the EOF things? DO i need to use DataGridView? Becoz the code i did didn't use DataGridView at all. i dont want the records to be displayed, i just want it to running behind.
No you do not need a worry about EOF or using a DataGridView. Just as you can use an ExecuteNonQuery method to insert multiple rows you can also do the same when using DELETE.
Data manipulation statements such as INSERT, UPDATE and DELETE do not generate a result set and hence you would normally use ExecuteNonQuery to run them. All the data manipulation runs in the database server engine.
If I understand correctly you need all data from table1 in table2 and then delete table1.
Options
1) It you need it once you could rename table1 to table2 and recreate table1
-- move the records to table 2, ok I assume it does not exist;)
RENAME TABLE table1 TO table2;
-- Create new table1 with same structure as table 2
CREATE TABLE table1 AS SELECT * FROM table2 WHERE 1=2;
2) Do a separate copy and delete assuming you have something like a primary key
-- copy the records
INSERT table2(field1, field2, ...) SELECT field1, field2, ... FROM table1;
-- and delete them
DELETE FROM table1;
3) Do it using C# but as this seems a database problem to me I would not go that far in pulling all the records to the client and then throwing them back.
DELETE FROM tblSend WHERE id = 5;
This will delete all rows that match the WHERE condition.
I am not sure I understand the relevance of the DataGridView. If it is databound, it will automatically remove the records as well. You only need to issue the delete query once and the rest should happen automatically, assuming you have the databinding correct.
What do you mean by "if they exist"? Compared to what?
To delete multiple records from table 1, you have to make a loop which goes through your table and compare.
Pseudo code:
forach (whatever as whut)
row = select whatever from table1.
if (whut == row)
copy row from table 1 to table 2;
Delete from table 1 where whut.id == row.id;
DELETE FROM tblSend WHERE id = 5;
This is the one solution for deletion a record.
If you want to set the identity key to 0 again, use this code
DBCC CHECKIDENT('tblSend', RESEED, 0);
Then press F5,

why sql delete query is not working

I have a table table1 with fields id(int), name(nchar), grade(real).
The following code isn't working. There are no errors or warnings. The code executes well but the number of affected rows = 0.
MsSql Server
sqlConnection1.Open();
SqlCommand cmd = new SqlCommand("Delete from [table1] where [id] = 1", sqlConnection1);
int c = cmd.ExecuteNonQuery();
sqlConnection1.Close();
All other queries are working well.
A slight expansion of what others have already asked. Are you certain that there are records to be deleted in your target table? Moreover, are you certain you are getting the table from the right database? It's possible the default is tempdb, for instance, and that just happens to have a table with the target name and with an id column.
First do a select from the SQL prompt to insure there are items of the type you are looking for:
SELECT TOP 10 * FROM [database].[schema].[table1] WHERE [id] = 1
If that provides results, try changing your command to explicitly state the database and schema as well:
DELETE FROM [database].[schema].[table1] WHERE [id] = 1
Thoughts:
is there a row with [id] 1
do you have a trigger that is firing?
my guess would be the second... the number is after triggers have been taken into account, and is the number of rows from the last operation.
I know this might sound silly, but is there data in the call with an ID of 1? Can you see it executing via SQL Profiler? What happens if you execute it via SSMS?
Does the query work when you run it in Sql Management studio?
Apart from Marc Gravell's comment about triggers you should also check, if there are foreign key constraints with ON DELETE RESTRICT` in place (and the error message somehow disappears before getting to you ...)

Categories