save DataTable to database - sql-server

Hi, I am generating a DataTable from a webservice and i would like to save the whole DataTable into one database table.
DataTable ds = //get info from webservice
The DataTable is getting generated but What to do next .I am getting stuck .Show me some syntax.I dont really need the select statement there either, i just want to insert all the info from the DataTable into a blank db table.

Use bulkcopy,
this is the code. And make sure that the table has no foriegn key or primary key constraints.
SqlBulkCopy bulkcopy = new SqlBulkCopy(myConnection);
bulkcopy.DestinationTableName = table.TableName;
try
{
bulkcopy.WriteToServer(table);
}
catch(Exception e){messagebox.show(e.message);}

This is exactly what SqlBulkCopy is for. Check it out: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx

Related

Write datatable to SQL Server - add new, update existing, remove missing

I have a SQL Server table that contains three columns:
PositionID, MeasureID, ModifiedDateTime
In my application I load this data into a DataTable and then add and remove rows to/from the DataTable. I would then like to write this back to the database.
The way I was doing it initially: delete all matching records for the PositionID and then loop and insert command with the all the data (or use Bulk Copy).
Is there a better way to do this more simply?
Try this one:
conn.Open();
SqlCommand cmd = new SqlCommand("Truncate Table SQLTableName", conn);
cmd.ExecuteNonQuery();
SqlBulkCopy bulkCopy = new SqlBulkCopy(conn);
bulkCopy.DestinationTableName = "SQLTableName";
bulkCopy.WriteToServer(datatableName);
"conn" is your connection to SQL-server.

In vb.net, why am I getting a duplicate key error when I have used a revised key?

I am using Visual Studio 2015 Community edition and programming in vb.net using ms sql-server 2015. I have set up the data adapter and data table in the form load event. (see below)
Private m_DABinders As New SqlDataAdapter
Private m_CBBinders As New SqlCommandBuilder
Private m_DataTableBinders As New Data.DataTable
I use the code below to insert a row into the Binders table and to check and handle the duplicate key problem. This works fine. My problem comes up when after I get this error, I change the key value to something unique and try to add the row again, and I still get the same duplicate key error, which, strangely enough, shows the original duplicate key value rather than the new one. (I have used MessageBox to ensure that the updated key value is being placed into the appropriate column.) It behaves as if it's still trying to insert the row with the duplicate key before it inserts the updated row.
Do I somehow have to remove the "bad" row from the data adapter or data table after the error? I notice by doing a row count that the rows on the data table goes up by one each time I get this error so I'm thinking I have to delete it somehow but I'm not sure how.
I'm very new to programming in vb.net and with ms sql-server so please don't assume much prior knowledge in your replies. Thanks.
Here is the sub-routine that I use to insert the row.
Public Sub CreateBinderRow()
Try
Dim keyValueBinder = tbLocation.Text & tbProject.Text & tbBinder.Text
Dim drNewBinderRow As DataRow = m_DataTableBinders.NewRow()
drNewBinderRow("KeyValue") = keyValueBinder
drNewBinderRow("Location") = tbLocation.Text
drNewBinderRow("ProjectName") = tbProject.Text
drNewBinderRow("BinderName") = tbBinder.Text
drNewBinderRow("LastUpdated") = Now
m_DataTableBinders.Rows.Add(drNewBinderRow)
m_DABinders.Update(m_DataTableBinders)
boolCreateBinderOK = True
Catch dbException As System.Data.SqlClient.SqlException
boolCreateBinderOK = False
MessageBox.Show("SQLException: " & dbException.ToString)
MessageBox.Show("Error creating Binder row - probably duplicate values", "Binder - Error Creating Binder Row",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch dbException As Exception
boolCreateBinderOK = False
MessageBox.Show("SQLException: " & dbException.ToString)
MessageBox.Show("Error creating Binder row", "Binder - Error Creating Binder Row",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
BTW - The error I am getting is: SqlException (0x80131904) Violation of Primary Key constraint 'PK.Binders' Cannot insert duplicate key in object 'dbo.Binders'. The duplicate key value is (my data). The statement has been terminated.
I think you need to commit the changes to the DataTable before updating the
DataSet.
m_DataTableBinders.Rows.Add(drNewBinderRow)
//add this line to commit the changes
m_DataTableBinders.AcceptChanges()
m_DABinders.Update(m_DataTableBinders)
Typically you would not hold a long-term reference to your DataTable.
A common code pattern using ADO.NET for database updates looks like:
Using connection As SqlConnection = New SqlConnection("connection string")
connection.Open
Using command As SqlCommand = New SqlCommand("INSERT INTO Binders (KeyValue, Location, ProjectName, BinderName, LastUpdated) VALUES (#KeyValue, #Location, #ProjectName, #BinderName, #LastUpdated)", connection)
command.Parameters.AddWithValue("#KeyValue", keyValueBinder)
' TODO: Add the rest of the command parameters '
command.ExecuteNonQuery
End Using
End Using

How to get the auto increment primary key in old mdb database?

I have to retrieve the Auto_Increment primary key (id) after inserting a new row in a mdb access database.
Having mdb file in the old Access 97 version too, I cannot use "SELECT ##Identity;", because it is not supported.
Besides, in a multi users environment I do not like the idea to use Max(ID).
Actually the only solution I have, it is to use the DAO as:
Dim db As Database 'Test Database
Dim rs As Recordset 'Test Table
...
rs.AddNew
id = rs!id
but I have to add a reference to the DAO COM DLL, while I would like to have a full managed .NET code.
Do you have any suggestion how to retrieve the Auto_Increment primary key (after inserting a new row) without using DAO or Max(ID)?
Here my code to add a new row:
Using oConn As New OleDbConnection(m_ConnString)
oConn.Open()
Using cmd As New OleDbCommand(sqlInsert, oConn)
cmd.ExecuteNonQuery()
End Using
End Using
Thank you.
If there is any other mandatory field in this table that has a unique index, you may query its value after your insertion with something like DFirst("ID", "tablename", "myfield = givenvalue"). If you're running in a transaction, use a recordset (perhaps the same as for the insertion) instead of DFirst.

Change datatable and tableadapter schema at runtime according to stored procedure. C#

I have DataSet and TableAdapter for the table in that DataSet. The problem is that TableAdapter uses a stored procedure to fill DataTable, but the amount of returned columns can be different.
How can I change the schema of DataTable at runtime to get all the columns from stored procedure?
In my opinion, drop the idea of using the DataAdapter, it's completely unnecessary. Do this to get the DataTable instead:
using(SqlConnection con = new SqlConnection("Conectionstring"))
{
con.Open();
using (SqlCommand commnand= new SqlCommand("StoredProcName",con))
{
command.CommandType=CommandType.StoredProcedure;
SqlDataReader reader = command.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
return table;
}
}
Now it doesn't matter the # of columns you return from the proc, the datatable will contain all of them.
EDIT: Add the following section to your Web.config file below the <configuration> section replacing the actual connectionString for yours. You should be able to copy this from the Your Settings file.
And now create your SqlConnection as follows:
SqlConnection con
= new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
Notice that "ConnectionString" is the name attribute of the connection string in the Web.Config.
See another example here, in case is not very clear.

Update from DataGridView with SqlDataAdapter

I have a DataGridView that displays data from a SQL Server database. It allows the user to edit the data and save it back to the database.
The way that data gets saved back to the database is something like this:
Dim da As New SqlDataAdapter
Dim cmdBuilder As New SqlCommandBuilder(da)
da.SelectCommand = New SqlCommand(sql, conn)
da.InsertCommand = cmdBuilder.GetInsertCommand
da.UpdateCommand = cmdBuilder.GetUpdateCommand
Dim cb As SqlCommandBuilder = New SqlCommandBuilder(da)
da.Update(dt)
This works fine when I'm saving to ordinary tables. However I also want to save to a view that has an INSTEAD OF trigger that fires on insert, update and delete. When I try to use the above with this view I get the error:
Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
How can I save to this view? I don't want to save directly to the underlying table because I want the trigger to fire.
Thanks!
EDIT: I also tried manually generating the InsertCommand and UpdateCommand, but got the same error.
EDIT 2: It turned out I got the commands wrong when I manually generated them. Once I fixed that it worked fine - my view gets updated and the trigger fires as expected. I guess that you just can't autogenerate the commands for a view with SqlCommandBuilder.
a quick google search shows that this problem may occur if your table does not have a primary key value. your select query must return that value for the update query (in a case where there is no primary key column, it wouldnt.)
http://social.msdn.microsoft.com/Forums/en-NZ/Vsexpressvcs/thread/5dec5633-ac84-48d9-8fd6-5c7601be4ccd

Resources