C# sqldataadapter datatablemapping - c#

I have a query - "SELECT PK1 FROM users";
I also have a datatable named myTable with three fields of type int;
-----------
| myTable |
-----------
| field1 |
| field2 |
| field3 |
-----------
For each row returned from my query, I would like to put the PK1 value into field2 in myTable leaving field1 and field3 null.
Here's some sample code I have tried so far, but it doesn't seem to be working. Instead, the field PK1 is appended to the end of myTable as a new field.
class Program
{
static void Main(string[] args)
{
string SQL = "SELECT PK1 FROM users";
SqlConnection connection = new SqlConnection([my connection string]);
DataTable myTable = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(SQL, connection);
myTable.Columns.Add("field1", typeof(Int32));
myTable.Columns.Add("field2", typeof(Int32));
myTable.Columns.Add("field3", typeof(Int32));
DataTableMapping dataMapping = adapter.TableMappings.Add("myTable", "users");
dataMapping.ColumnMappings.Add("PK1", "field2");
adapter.Fill(myTable);
foreach (DataRow row in myTable.Rows)
{
Console.WriteLine("------------");
foreach (DataColumn column in myTable.Columns)
{
Console.WriteLine(column.ColumnName + " : " + row[column]);
}
}
Console.ReadKey();
}
}
Is there an issue in my code, or is there another way I can map the fields across?
This is a simplified example for the purposes of this question, as such mapping the field names would be ideal rather than inserting the value at a given position.

I think if it is your requirement then there is nothing wrong with this approach.
Change your query to the following, and you don't need the mapping.
string SQL = "SELECT PK1 as field2 FROM users";

it is adding the column because you are telling it to. You should either use the datamappingColumn feature or the table.column.add feature not both, they are redundant, and probably not necessary.
So if you leave the table.column.add()
Here is an example of how you would "bind" the column names to the columns you set in table, you specify the order in which you want them to appear, you can leave them blank by "" double quote or set them to null by using NULL.
this.table.AutoSetDataBoundColumnHeaders = true;
this.table.SetDataBinding(table, null, "PK1", null);

Related

Test a value of multiple columns, Access SQL from Visual Studio

I want to import a table from Access DB, in this table there is a column that is valued and not, when not I want to fill this column on the result table with a default value or let it empty.
I tried IsNull(col2 ,'')
Thanks in advance
MyQuery = "SELECT col1 AS col1, col2 AS myDevice";
MyQuery += " FROM table 1";
OleDbCommand cmd1 = new OleDbCommand(MyQuery, conn);
OleDbDataAdapter adapter1 = new OleDbDataAdapter(cmd1);
adapter1.Fill(table);
DB.Tables.Add(table);
In MS Access, you want the Nz() function:
Nz(col2 ,'default')
IsNull() exists in Access but it is meant to check if a value is null (and it returns a boolean value).
I solved with this:
MyQuery = "SELECT col1 AS col1, IIF(ISNULL(col2), 0, col2) AS myDevice";
Thanks

SQL Server - Update table and return the Updated rows

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.

Dynamic SQL with choosing multiple dropdowns in C#

Hie I'm new to ASP.Net and needed some help.
Here is my problem: I have 4 drop downs in my application, a button saying search, grid view to show the results. I was trying to filter the results based on the value of drop downs.
So i wrote the query as "select * from table where column1=dd1.SelectedItem.Value" but the tricky part is i want the results to be displayed even if one of the drop down is selected or two of them is selected or all of them is selected. How do i write the Where Part in my SQL query?? I know that I have to use dynamic SQL but i have no clue about dynamic SQL.
Use something like this
string q = #"
SELECT * FROM table
WHERE
(#value1 IS NULL OR column1 = #value1)
AND
(#value2 IS NULL OR column2 = #value2)
AND
(#value3 IS NULL OR column3 = #value3)
";
var command = new SqlCommand();
command.CommandText = q;
command.Parameters.AddWithValue("#value1", dd1.SelectedItem.Value);
command.Parameters.AddWithValue("#value2", dd2.SelectedItem.Value);
command.Parameters.AddWithValue("#value3", dd3.SelectedItem.Value);
First you should store dd1.SelectedItem.Value in a variable as
string v = dd1.SelectedItem.Value.ToString();
then create a string for your query as
string q = "select * from table where (column1 is null or column1=" + v + ")";
then use this code:
SqlCommand com = new SqlCommand(q, yoursqlconnection);
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);

What method can be used to specifically insert data into your C# DataGridView from SQL?

Problem:
Code works fine, however, when I launch my program my two predefined columns Course_ID and File_Count are present in my then blank dataGridView. There is also an empty default row.
Whenever I run my query, my dataGridView is getting an extra column created and an extra row created. The result from the query goes into this new third column on the first row which is weird.
See here:
http://imgur.com/UBFI8Nz
Here is my code:
string[] courses = txtBoxCourses.Text.Split(',');
SqlConnection myConnection = new SqlConnection("user id=userid;" +
"password=password;server=myserver;" +
"Trusted_Connection=no;" +
"connection timeout=30");
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
myCommand.Connection = myConnection;
DataTable t = new DataTable();
foreach (string line in courses)
{
myCommand.CommandText = "DECLARE #CourseName varchar(80); Set #CourseName = '"+line+"' SELECT COUNT(*) FROM ( SELECT FILE_ID,PARENT_ID ,PATH_ID,FULL_PATH ,FILE_NAME FROM BBLEARN_cms_doc.dbo.XYF_URLS WHERE FULL_PATH like '/courses/'+#CourseName+'/%') as subquery;";
adapter.Fill(t);
dataGridView1.DataSource = t;
}
What I want to happen is I want to fill in the first column with the values from my string[] courses list and I want it to correspond with the result from the query in my foreach statement. For example, if I use two course IDs to query, test1 and test2 I'd prefer this:
Course_ID file_count
test1 234
test2 1478
I've looked into using the DataPropertyName property but I don't think that's it.
Try changing your select to:
SELECT #CourseName as Course_ID, COUNT(*) as File_Count FROM (
SELECT FILE_ID,PARENT_ID ,PATH_ID,FULL_PATH ,FILE_NAME FROM BBLEARN_cms_doc.dbo.XYF_URLS
WHERE FULL_PATH like '/courses/'+#CourseName+'/%') as subquery;
Your current query is returning an integer and your grid view doesn't see it attached to any of your predefined columns. Try aliasing the columns with the column name in the grid view. That should tie your sql results to your current columns.

How do I retrieve DataColumn.DefaultValue from a Sql Table?

Is there a way to determine a column's defaultvalue from the Sql Database using ado.net?
I tried using the SqlDataAdapter's FillSchema method:
using (SqlDataAdapter adapter = new SqlDataAdapter()) {
adapter.SelectCommand = myConnection.CreateCommand();
adapter.SelectCommand.CommandType = CommandType.Text;
adapter.SelectCommand.CommandText = "SELECT * FROM myTable";
DataTable table = new DataTable();
adapter.Fill(table);
adapter.FillSchema(table, SchemaType.Mapped);
}
When I inspect the DataColumns in the DataTable, I can determine if a column is an AutoIncrement, and can determine if it allows nulls using the AllowDBNull property. However, DefaultValue (for columns that I know have a default value) is always null.
I considered:
DataTable schemaTable = null;
using (SqlDataReader reader = adapter.SelectCommand.ExecuteReader(CommandBehavior.SchemaOnly)) {
schemaTable = reader.GetSchemaTable();
reader.Close();
}
but DefaultValue is not included in the schema.
So...how can I get a column's DefaultValue?
Use this query to interrogate the INFORMATION_SCHEMA for the info you're looking for:
SELECT
TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'your table name' AND
COLUMN_NAME = 'your column name'
Marc
Not really. This is because the default value can be determined at the time a record is inserted (like a GETDATE() or NEW_ID()). So the value cannot be determined in advance.
The COLUMN_DEFAULT column of INFORMATION_SCHEMA.COLUMNS gives you not the actual default value, but a string representation of the code SQL Server and the likes will execute to generate the default value. See http://msdn.microsoft.com/en-us/library/ms188348.aspx.
Having said that, simple constant values can easily be deduced from such an expression.

Categories