I have been trying to use OleDbDataAdapter to update a DataTable but got confused about the commands.
Since I sometimes get info from diffrent tables I can't use a CommandBuilder.
So I have tried to create the commands on my on but found it hard with the parameters.
DataTable.GetChanges returns rows that needs to use an INSERT or an UPDATE command - I guess I can't distinct between them.
I need you to complete the following:
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter();
// Here I create the SELECT command and pass the connection.
da.Fill(dt);
// Here I make changes (INSERT/UPDATE) to the DataTable (by a DataGridView).
da.UpdateCommand = new OleDbCommand("UPDATE TABLE_NAME SET (COL1, COL2, ...) VALUES (#newVal1, #newVal2, ...) WHERE id=#id"); // How can I use the values of the current row (that the da is updating) as the parameters (#newVal1, #newVal2, id....)?
Thank you very much!
The data adapter can work in conjunction with the datatable. As such, I've actually wrapped mine together into a class and works quite well. Aside from the complexities of my stuff, here's a snippet that might help you along. When adding a parameter, you can identify the column source that the data is coming from FROM the DataTable. This way, when a record is internally identified as "Added" or "Updated" (or "Deleted"), when you build your SQL Insert/Update/Delete commands, it will pull the data from the columns from the respective rows.
For example. Say I have a DataTable, primary Key is "MyID" and has columns "ColX, ColY, ColZ". I create my DataAdapter and build out my select, update, delete commands something like... (? is a place-holder for the parameters)
DataAdapter myAdapter = new DataAdapter()
myAdapter.SelectCommand = new OleDbCommand();
myAdapter.InsertCommand = new OleDbCommand();
myAdapter.UpdateCommand = new OleDbCommand();
myAdapter.DeleteCommand = new OleDbCommand();
myAdapter.SelectCommand.CommandText = "select * from MyTable where MyID = ?";
myAdapter.InsertCommand.CommandText = "insert into MyTable ( ColX, ColY, ColZ ) values ( ?, ?, ? )";
myAdapter.UpdateCommand.CommandText = "update MyTable set ColX = ?, ColY = ?, ColZ = ? where MyID = ?";
myAdapter.DeleteCommand.CommandText = "delete from MyTable where MyID = ?";
Now, each has to have their respective "Parameters". The parameters have to be addded in the same sequence as their corresponding "?" place-holders.
// Although I'm putting in bogus values for preparing the parameters, its just for
// data type purposes. It does get changed through the data adapter when it applies the changes
OleDbParameter oParm = new OleDbParameter( "myID", -1 );
oParm.DbType = DbType.Int32;
oParm.SourceColumn = "myID"; // <- this is where it looks back to source table's column
oParm.ParameterName = "myID"; // just for consistency / readability reference
myAdapter.SelectCommand.Parameters.Add( oParm );
do similar for rest of parameters based on their types... char, int, double, whatever
Again, I have like a wrapper class that handles managment on a per-table basis... in brief
public myClassWrapper
{
protected DataTable myTable;
protected DataAdapter myAdapter;
... more ...
protected void SaveChanges()
{
}
}
Its more complex than just this, but during the "SaveChanges", The datatable and dataAdapter are in synch for their own purposes. Now, flushing the data. I check for the status of the table and then you can pass the entire table to the dataAdapter for update and it will cycle through all changed records and push respective changes. You'll have to trap for whatever possible data errors though.
myAdapter.Update( this.MyTable );
As it finds each "changed" record, it pulls the values from the Column Source as identified by the parameter that is found in the table being passed to the adapter for processing.
Hopefully this has given you a huge jump on what you are running into.
---- COMMENT PER FEEDBACK ----
I would put your update within a try/catch, and step into the program to see what the exception is. The message adn/or inner exception of the error might give more info. However, try to simplify your UPDATE to only include a FEW fields with the WHERE "Key" element.
Additionally, and I oopsed, missed this from first part answer. You might have to identify the datatable's "PrimaryKey" column. To do so, its a property of the DataTable that expects and array of columns that represent the primary key for the table. What I did was...
// set the primary key column of the table
DataColumn[] oCols = { myDataTbl.Columns["myID"] };
myDataTbl.PrimaryKey = oCols;
I would comment out your full update string and all its parameters for your UPDATE. Then, build it with just as simple as my sample of only setting 2-3 columns and the where clause
myAdapter.UpdateCommand.CommandText = "update MyTable set ColX = ?, ColY = ? where MyID=?";
Add Parameter object for "X"
Add Parameter object for "Y"
Add Parameter object for "MyID"
Pick fields like int or char so they have the least probability of problems for data type conversions, then, once that works, try adding all your "int" and "character" columns... then add any others. Also, which database are you going against. SOME databases don't use "?" as placeholder in the command but use "named" parameters, some using
"actualColumn = #namedCol"
or even
"actualColumn = :namedCol"
Hope this gets you over the hump...
You could use the String.Format Method to replace the #newVal1, #newVal2, ... in your code, like this da.UpdateCommand = new OleDbCommand(String.Format("UPDATE TABLE_NAME SET (COL1, COL2, ...) VALUES ({0}, {1}, ...) WHERE id=#id",OBJECT_ARRAY_CONTAINING_VALUES_FROM_THEDG));
[Eidt per comment]
To handle the row[0], row[1] you need a loop like:
for(i=0; i<rows.Count; i++)
{
da.UpdateCommand = new OleDbCommand(String.Format("UPDATE...",row[i]);
da.Update(dt);
}
Related
I have a SQL Server database which has a lot of information inside.
I want to select top 50 rows in a single query (which I did, with no problem) but then I want to update a column from false to true, so next time I select I wont select the same, my code looks like this:
string Command = "UPDATE HubCommands SET [Alreadytaken] = 'true' FROM (SELECT TOP 50 [CommandId],[DeviceId],[Commandtext], [HashCommand],[UserId] FROM HubCommands) I WHERE [HubId] = '18353fe9-82fd-4ac2-a078-51c199d9072b'";
using (SqlConnection myConnection = new SqlConnection(SqlConnection))
{
using (SqlDataAdapter myDataAdapter = new SqlDataAdapter(Command, myConnection))
{
DataTable dtResult = new DataTable();
myDataAdapter.Fill(dtResult);
foreach (DataRow row in dtResult.Rows)
{
Guid CommandId, DeviceId, UserId;
Guid.TryParse(row["CommandId"].ToString(), out CommandId);
Guid.TryParse(row["DeviceId"].ToString(), out DeviceId);
Guid.TryParse(row["UserId"].ToString(), out UserId);
Console.WriteLine("CommandId" + CommandId);
}
}
}
This code does work, and it updates what I ask it to update, but I don't get nothing in the data table, its like it is always updating but not selecting.
If I do a normal select it does work and give information.
Does anyone have any idea how to update and get some data back, in a single query?
So your question is:
How can I update a table in SQL Server using C# and return the truly updated
rows as a DataTable ?
First You have multiple issues in your query.
You should use 1 and 0, not true or false. SQL-Server has a bit datatype and not a Boolean.
Second, this is how you should've constructed your query:
DECLARE #IDs TABLE
(
[CommandId] uniqueidentifier
);
INSERT INTO #IDs
SELECT [CommandId] FROM HubCommands
WHERE [HubId] = '18353fe9-82fd-4ac2-a078-51c199d9072b' AND [Alreadytaken] = 0;
UPDATE HubCommands
SET [Alreadytaken] = 1
WHERE CommandId IN
(
SELECT [CommandId] FROM #IDs
);
SELECT * FROM HubCommands
WHERE CommandId IN
(
SELECT [CommandId] FROM #IDs
);
Wrap all the above in a single string and use SqlDataReader. No need for an Adapter in you case (Since we're mixing commands unlike what the adapter usually does):
var sqlCommand = new SqlCommand(Command, myConnection);
SqlDataReader dataReader = sqlCommand.ExecuteReader();
DataTable dtResult = new DataTable();
dtResult.Load(dataReader);
I highly advise you to create a stored procedure accepting HubId as a parameter that does all the above work. It is neater and better for maintenance.
I have a stored proc which accepts user defined table type and default values for all the columns in the user defined data type is set to null.
Now i am passing a dataTable with less columns to stored procedure from c# code expecting that the values for remaining columns will be set to null.
But i am getting this error:
Trying to pass a table-valued parameter with 21 column(s) where the corresponding user-defined table type requires 77 column(s).
This is the code
SqlConnection conn = new SqlConnection("server=****; database=***;integrated security=SSPI");
DataSet dataset=new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand("Insert");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
SqlParameter para = new SqlParameter();
para.ParameterName = "#TableVar";
para.SqlDbType = SqlDbType.Structured;
//SqlParameter para=cmd.Parameters.AddWithValue("#TableVar",table);
para.Value = table;
cmd.Parameters.Add(para);
cmd.ExecuteNonQuery();
You can use a SqlDataAdapter to create a DataTable matching the table type schema:
DataTable table = new DataTable();
// Declare a variable of the desired table type to produce a result set with it's schema.
SqlDataAdapter adapter = new SqlDataAdapter("DECLARE #tableType dbo.UserDefindTableType
SELECT * FROM #tableType", ConnectionString);
// Sets the DataTable schema to match dbo.UserDefindTableType .
adapter.FillSchema(table, SchemaType.Source);
You can then create DataRows with the all the default column values and just set the columns you know about:
DataRow row = table.NewRow();
// Set know columns...
row["ColumnName"] = new object();
// or check column exists, is expected type etc first
if (table.Columns.Contains("ColumnName")
&& table.Columns["ColumnName"].DataType == typeof(string)) {
row["ColumnName"] = "String";
}
table.Rows.Add(row);
I'm having the same issue and the solution I'm working on is to run an extra SQL query to get the column definition and then fill up the DataTable with the missing columns, here is the SQL statement for a column definition on your table type:
select c.name, t.name as type, c.max_length as length from sys.table_types tt
inner join sys.columns c on c.object_id = tt.type_table_object_id
inner join sys.types t on t.system_type_id = c.system_type_id
where tt.name = #tabletypename
order by c.column_id
The C# code will be a bit more messy as you have to parse the return type (ie VARCHAR, INT, etc) into a SqlDbType enum if you want the solution to work for all table valued parameter defintions..
I would have thought stuff like this could have been better solved by Microsoft inside the SQL Server engine as its the next best way to import CSV files if you do not have write access to the local filesystem, but I want a single UDTT to cater for all CSV files not having to create a new table type every time I deal with a new file format. Anyways.. rant over.
I am attempting to update a simple ms access database. I get an Exception on certain tables that, after searching, I found Microsoft Support - Syntax Error. I believe it means that one of the column names uses a reserved word. This seems to be the case, since all the tables update except the ones with "GUID" as one of the column names, a reserved word. This page also states that I should be using a OleDbAdapter and DataSet, which should solve the problem. Unfortunately I cannot change the name of the column. That is beyond my control, so I have to work with what is given me.
I haven't had to do work with databases much, and everything I know I've learned from examples from the internet (probably bad ones at that). So what is the proper way to update a database using OleDbAdapter and dataSet?
I don't think I should be using DataTable or OleDbCommandBuilder, and I believe the solution has something to do with parameters. But my googleing skills are weak.
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; " +
Data Souce=" + source);
conn.Open();
OleDbAdapter adapter = new OleDbDataAdapter("SELECT * From " + table, conn);
OleDbCommandBuiler cmdBuiler = new OleDbCommandBuilder(adapter);
DataSet = new DatSet();
adapter.InsertCommand = cmdBuilder.GetInertCommand(true); // Is this necessary?
adapter.Fill( dataSet, table);
DataTable dataTable = dataSet.Tables[table]; // Do I need a DataTable?
DataRow row = dataTable.
row [ attribute ] = field; // Do this for all attributes/fields. I think this is wrong.
dataTable.rows.Add(row);
adapter.Update(dataTable); //<--"Syntax error in INSERT INTO statement." Exception
The problem may be that the column names (especially those whose name are reserved words) should be surrounded by square brackets. The OleDbCommandBuilder, when it creates its own InsertCommand, doesn't surround the names with brackets, so a solution is to manually define the OleDbDataAdapter's InsertCommand:
adapter.InsertCommand = new OleDbCommand(String.Format("INSERT INTO {0} ([GUID], [fieldName]) Values (#guid,#fieldName);", table), conn);
Defining parameters for each column and then manually adding the parameter's values;
adapter.InsertCommand.Parameters.Add(new OleDbParameter("#guid",row["GUID"]));
So summing up, for the tables which have a column named "GUID", you should try something like the following:
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Souce=" + source);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * From " + table, conn);
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(adapter);
adapter.InsertCommand = new OleDbCommand(String.Format("INSERT INTO {0} ([GUID], [fieldName]) Values (#guid,#fieldName);", table), conn);
DataTable dataTable = new DataTable(table);
adapter.Fill( dataTable);
DataRow row = dataTable.NewRow();
row [ fieldName ] = fieldValue;
// eg: row [ "GUID" ] = System.Guid.NewGuid().ToString(); // Do this for all attributes/fields.
dataTable.Rows.Add(row);
adapter.InsertCommand.Parameters.Add(new OleDbParameter("#fieldName",row[fieldName]));
// eg: adapter.InsertCommand.Parameters.Add(new OleDbParameter("#guid",row["GUID"]));
adapter.Update(dataTable);
As to problem #1. Try doing a full qualification of the column name i.e. table.columnName (that fixes the problem in MySQL so maybe it does in Access) also, try putting [ ] around the column name.
Select * is usually a poor option to specifying the column names and using aliases. For example use Select Column1 as 'Column1', Column2 as 'Column2' ....
this makes working with your dataset and datatable much easier as you can access the column by its alias instead of by column indexes.
I find that the DataAdapter is much more useful for filling datasets than for actually modifying a database. I recommend something like:
string updateQuery = "Update ..... Where ...."; //do your magic here
OldDbcommand command = new OleDbCommand(updateQuery);
command.Connection = conn;
conn.Open();
con.ExecuteNonQuery();
conn.Close();
You could fill your dataset with the adapter and then do as I just did to execute your update commands on the DB.
A good place to start would be using DataSetDesigner and Typed DataSets to start
try this walk through : http://msdn.microsoft.com/en-us/library/ms171893(v=vs.80).aspx
A good longterm approach is to use Sql Server Express instead, then you'll have a choice of using : Entity Framework, Linq To Sql or Still keep using the DataSetDesigner and Typed DataSets.
NOTE: This is the simple version of my previous question that SHOULD have been written.
I have two tables in the same SQL Server database, TestTable and TestTable2. Neither has a primary key. Each have two columns,
TestInt (int)
TestString (varchar(50))
There is data in TestTable2, while TestTable is empty. I want to copy the contents of one into the other, via C#. (I know this can be done in SQL, but humor me here.)
Here is the code I've written to do the job, using a SqlDataAdapter object...
// Data in TestTable2, nothing in TestTable.
private static void Main(string[] args)
{
SqlConnection conn = /* CONNECTION CREATION CODE */
string sqlQuery = "SELECT * FROM TestTable2";
DataTable payload = /* SIMPLE QUERY CODE USING sqlQuery */
// CODE CHECKPOINT #1
sqlQuery = "SELECT * FROM TestTable";
SqlCommand sCmd = new SqlCommand(sqlQuery, conn);
SqlDataAdapter sDA = new SqlDataAdapter(sCmd);
DataSet dataSet = new DataSet();
conn.Open();
sDA.Fill(dataSet);
conn.Close();
for (int i = 0; i < payload.Rows.Count; i++)
{
dataSet.Tables[0].ImportRow(payload.Rows[i]);
}
// CODE CHECKPOINT #2
SqlCommandBuilder cb = new SqlCommandBuilder(sDA);
conn.Open();
sDA.Update(dataSet);
conn.Close();
}
The problem is that this code is not working. If I were to check the contents of DataTable 'payload' at Checkpoint #1, I see 4 rows, while there are 0 rows in dataSet.Tables[0]. If I then check the contents of 'dataSet' at Checkpoint #2, I see 4 rows in dataSet.Tables[0]! However, at the end of the program, none of the rows from TestTable2 have made it into TestTable.
In other words, C# is moving the data between the DataTables, but it is having no affect on the tables themselves.
I've found that adding newly created rows
DataRow row = DataSet.DataTable.NewRow(...);
...
dataSet.Tables[i].Rows.Add(row);
into the destination DataSet works with SqlDataAdapter.Update, but that's not appropriate in this case, as you cannot use DataTable.Rows.Add on a row held by a separate DataTable. Hence, my problem, as this has rendered me incapable of transfering data from one table to another, especially in cases where large numbers of column are involved, rendering explicit SQL commands very clunky.
Is there something I'm missing in this code that I'm not seeing? If so, what is it?
Thanks.
Try DataSet.AcceptChanges() before updating data to the DB. Also, check, what the DataSet.GetChanges() method returns. It should not be an empty DataSet.
Finally, I have found the solution here:
importrow --> update fails
The ultimate answer is a translation of the link provided by platon. However, I'm including the explicit code here for easier future reference.
Basically, ImportRow doesn't always set the dirty bit for the added rows. As a result, SqlDataAdapter.Update won't necessarily move the changes to SQL since it doesn't recognize the new rows as changed data. To insure that the dirty bit is set, you need to call DataTable.Rows.Add, but as mentioned this cannot be called using the row of another table as a parameter.
What to do? Don't use the row as a parameter to Add(). Instead, use the object[] ItemArray...
for(int i = 0 ; i < srcTable.Rows.Count ; i++)
{
destTable.Rows.Add(srcTable.Rows[i].ItemArray);
}
...
SqlCommandBuilder sCB = new SqlCommandBuilder(adapter);
adapter.Update(dataSet);
I am using sqlconnection. I want to create a view and select from the view set.
Like I have shown below I have created a view called vwtopic.. from this I need to select distinct values of a column.
I cannot put in one easy statment because i need distinct values of topic column only and need to order by another column datetime..
So I am first creating a view where I am ordering by datetime and from this I am selecting distinct topic.
Problem is I am able to create a view set, but from this I am not able to select the distinct topic data to a SqlDataAdapter.. I frankly dont know the syntax.. I have not tried this before..
First part:
SqlConnection con = new SqlConnection("server=xxxx;database=wbsd;user id=***;password=***;");
SqlCommand add = new SqlCommand("CREATE VIEW vwtopic AS SELECT * FROM sr_topic_comment ORDER BY datetime DESC", con);
try
{
add.Connection.Open();
add.ExecuteNonQuery();
add.Connection.Close();
}
catch (System.FormatException)
{
}
Second part:
String sqlcmd = "SELECT DISTINCT topic FROM vwtopic WHERE owner='" + owner + "'";
SqlDataAdapter adap = new SqlDataAdapter(sqlcmd,con);
Instead of creating Views in Code, use the "WITH" statement or Sub-queries this should meets your needs:
WITH [vwtopic] AS (
SELECT * -- I recommend using each column name
FROM [sr_topic_comment]
-- not sure if ORDER BY is allowed here:
-- ORDER BY [datetime] DESC
)
SELECT DISTINCT [topic] FROM [vwtopic] -- add WHERE, ORDER BY
Since the view you are creating does not have any filters defined, selecting distinct values from the view is equivalent to selecting distinct values from the table. When selecting distinct values, you can only order by those values (not the datetime column as you're attempting here). Therefore, you can do:
SqlCommand cmd = new SqlCommand("SELECT DISTINCT topic FROM sr_topic_comment WHERE owner = #owner", con);
cmd.Parameters.Add(new SqlParameter(#owner, SqlDbType.Varchar, 25));
cmd.Parameters["#owner"].Value = owner;
DataSet ds = new DataSet();
using (SqlDataAdapter adap = new SqlDataAdapter(cmd)) {
adap.Fill(ds);
}
This will give you a DataSet filled with the distinct values from the table that meet the filter criteria (owner == the supplied owner).
I found the answer below will do the trick for me...
I am filling the result in dataset and calling my required column 'topic'..
SELECT DISTINCT topic,datetime FROM sr_topic_comment WHERE owner='sr' ORDER BY datetime DESC
Thank you very much for your inputs.. I learnt about WITH clause today.. cheers..