Does somebody know how to update a SQL database using a windows form?
I mean, I have a function to make the connection and when I use the select function it works, but I can't modify it.
I'm using this to add a new element "insert into [database name] ([name of the row]) values ([value I want to insert])"
please visit SQL Database Tutorial: Understanding Your Database Structure to understand how actually database store records.
Refer few syntax that may help you
to insert/update records in table
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
for update records in table
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
I had an question exactly about this thread asked by me -->How to take ID numbers from a SQL Server table using Visual C#.
Maybe it can help you it is worth having a look at it.
Related
I am facing an issue I hope to get it solved by here. I have 3 different tables in a DataSet and I want to insert it in the database table.
I know I can do this using SqlBulkCopy but there is a catch and that is I want to check if the data already exists in the database then I want it to get updated instead of insert.
And if the data doesn't exist in the database table, I want to insert it then. Any help on this would be appreciated.
I know I can iterate it through each record and then fire a procedure which will check for its existence if it exists den update or else insert. But the data size is huge and iterating through each record would be a time taking process, I don't want to use this approach.
Regards
Disclaimer: I'm the owner of the project Bulk Operations
This project allows to BulkInsert, BulkUpdate, BulkDelete, and BulkMerge (Upsert).
Under the hood, it does almost what #marc_s have suggested (Use SqlBulkCopy into a temporary table and perform a merge statement to insert or update depending on the primary key).
var bulk = new BulkOperation(connection);
bulk.BulkMerge(dt);
I want to some rows in a table , then select a specific data from the newly added record and then insert that data in another table.The following statement is obviously not working but it should give an idea of what i am trying to accomplish here.
cmd = new SqlCommand("INSERT INTO SalesDetails.sale(sale_date) VALUES (#sale_date);
SELECT sale_id FROM SalesDetails.sale WHERE sale_date=#sale_date;
SELECT stock_id FROM StockDetails.stock_item WHERE item_id=#item_id;
INSERT INTO SalesDetails.payment(payment_method,sale_id)
VALUES (#payment_method, sale_id);
INSERT INTO SalesDetails.dispatch_out_item(stock_id,sale_id,qty)
VALUES (stock_id,sale_id,#qty);", con);
Rather than writing eveything into one single SQL Command statement, I would suggest you to write a Stored Procedure for this.
The reason behind using a stored procedure is that you can more cleanly and nicely handle multiple table transactions in it while also implementing the Transaction logic through which you can ensure data consistency of all the tables where the changes will be taking place. Since you are manipulating multiple tables here, you need to make sure that the change is preserved in all tables or in none of them.
Check this link as a reference : Using Stored Procedures with Transactions
Hope this helps.
I am using Linq To Sql to insert few data to a table in Sql server 2008.
memadd.add_id = Convert.ToDecimal(resadd);
memadd.mem_add = txtResAdd.Text;
memadd.tel_no1 =Convert.ToDecimal(txtResTelNo.Text);
memadd.mob_no1 = Convert.ToDecimal(txtResMobNo.Text);
memadd.state = drpResState.Text;
memadd.city = drpResCity.Text;
memadd.pin_no = Convert.ToDecimal(txtResPinNo.Text);
dt.mem_addresses.InsertOnSubmit(memadd);
dt.SubmitChanges();
My issue here is that when i insert data into the field , it gives me an error saying
Can't perform Create, Update or Delete operations on 'Table(mem_address)' because it has no primary key.
I have a situation wherein i cant set primary key to that table .Can anyone please point me out what needs to be done here.
Thanks
Just tell the memadd table in the DBML designer to select add_id as a PK for example.
It needs not be on the database itself.
Linq to sql can't be used in such situations. Just warp your insert statement into a stored procedure and add the procedure to your data model. If you can't do that, write a normal function with a bit of in-line SQL
Linq does not support table w/o primary keys...
I am fairly new to C# and SQL, so this may be a very easy question to answer.
I am trying to add a row to a table (EventList) through C# code. I have opened my SqlConnection without any issues, and I know I am connected to the correct database as some earlier code is querying for rows in one of the tables and it's returning the correct keys.
The SQL query to insert the row into the table is like this:
sqlCmd.CommandText =
"insert into EventList values ('" +
eventListIdentifier + "','" +
eventId.ToString() + "')";
sqlCmd.ExecuteNonQuery();
I am using SQL Server Management Studio Express to view the tables in my database. After running the above query, I right-click on the EventList table and click Open Table.
I am not seeing the new row added based on the above call. Any ideas what I may be doing wrong?
Update 1
The data types I'm inserting are:
eventListIdentifier (varchar(100), null)
eventId (varchar(8000), null)
I manually created the same query in SSMS like this:
insert into EventList(eventListIdentifier, eventId ) values('test', 'blah')
and says the following:
(1 row(s) affected)
However no row has been added to the table when I right-click on it and open it.
Update 2
Output of System.Console.WriteLine(sqlCmd.CommandText); as requested by #billinkc:
insert into EventList(eventListIdentifier, eventId) values ('7/09/2011 10:43:55 AM','7')
Any errors? What happens if you output the SQL statement instead of executing it and copy/paste it into SSMS?
Try specifying the columns in the insert:
insert into EventList(col1, col2) values (...)
Also, use parameters instead of string concatenation. The reasons for doing so are well documented in about 200000 questions here already. Just search for SQL injection.
Don't use Open Table due to the cache/refresh bug I pointed out in my comment. Just re-run the same query in a query window:
SELECT * FROM dbo.EventList
-- WHERE EventId = <EventId>
;
You haven't really provided enough detail to help. At the least, it would be helpful to know:
Are there any errors?
Is the code snippet you posted in a try/catch block?
What datatypes are the variables you are inserting?
Are you using a Transaction that wasn't committed?
Finally, how is the table sorted? Are there any indexes, including a primary key?
If you run a SELECT in Management Studio based on the value in eventId, do you see the record?
I'm stuck on a little problem concerning database.
Once a month I get a XML file with customer information (Name, address, city,etc.). My primary key is a customer number which is provided in the XML file.
I have no trouble inserting the information in the database;
var cmd = new SqlCommand("insert into [customer_info]
(customer_nr, firstname, lastname, address_1, address_2, address_3.......)");
//some code
cmd.ExecuteNonQuery();
Now, I would like to update my table or just fill it with new information. How can I achieve this?
I've tried using TableAdapter but it does not work.
And I'm only permitted to add one XML because I can only have one customer_nr as primary key.
So basically how do I update or fill my table with new information?
Thanks.
One way would be to bulk insert the data into a new staging table in the database (you could use SqlBulkCopy for this for optimal insert speed). Once it's in there, you could then index the customer_nr field and then run 2 statements:
-- UPDATE existing customers
UPDATE ci
SET ci.firstname = s.firstname,
ci.lastname = s.lastname,
... etc
FROM StagingTable s
INNER JOIN Customer_Info ci ON s.customer_nr = ci.customer_nr
-- INSERT new customers
INSERT Customer_Info (customer_nr, firstname, lastname, ....)
SELECT s.customer_nr, s.firstname, s.lastname, ....
FROM StagingTable s
LEFT JOIN Customer_Info ci ON s.customer_nr = ci.customer_nr
WHERE ci.customer_nr IS NULL
Finally, drop your staging table.
Alternatively, instead of the 2 statements, you could just use the MERGE statement if you are using SQL Server 2008 or later, which allows you to do INSERTs and UPDATEs via a single statement.
If I understand your question correctly - if the customer already exists you want to update their information, and if they don't already exist you want to insert a new row.
I have a lot of problems with hard-coded SQL commands in your code, so I would firstly be very tempted to refactor what you have done. However, to achieve what you want, you will need to execute a SELECT on the primary key, if it returns any results you should execute an UPDATE else you should execute an INSERT.
It would be best to do this in something like a Stored Procedure - you can pass the information to the stored procedure at then it can make a decision on whether to UPDATE or INSERT - this would also reduce the overhead of making several calls for your code to the database (A stored procedure would be much quicker)
AdaTheDev has indeed given the good suggestion.
But in case, you must insert/update from .NET code then you can
Create a stored procedure that will handle insert/update i.e. instead of using a direct insert query as command text, you make a call to stored proc. The SP will check if row exists or not and then update (or insert).
User TableAdapter - but this would be tedious. First you have to setup both insert & update commands. Then you have to query the database to get the existing customer numbers and then update the corresponding rows in the datatable making the Rowstate as Updated. I would rather not go this way.