how to print single value of data set - c#

conn = new SqlConnection(#"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true");
ada = new SqlDataAdapter("select total_amount from debit_account where account_no=12", conn);
ds = new DataSet();
ada.Fill(ds);
Now, I want to print value of the dataset... how? Please help me.

I'd suggest that the best option here isn't actually a SqlDataAdapter and DataSet, but rather a SqlCommand. Try this:
using(SqlConnection conn = new SqlConnection(#"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true"))
{
conn.Open()
using (SqlCommand command = new SqlCommand("select total_amount from debit_account where account_no=12", conn)
{
var result = command.ExecuteScalar();
Console.WriteLine("The total_amount for the account is {0}", result);
}
}
The ExecuteScalar() method on SqlCommand returns the value in the first column of the first row that your query returns, which is ideal in this situation.
If you absolutely have to use a dataset then you'd want to do the following:
using(SqlConnection conn = new SqlConnection(#"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true"))
{
conn.Open()
using (SqlDataAdapter adapter = new SqlDataAdapter("select total_amount from debit_account where account_no=12", conn)
{
var ds = new DataSet();
adapter.Fill(ds);
Console.WriteLine("The total_amount for the account is {0}", ds.Tables[0].Rows[0][0]); // Get the value from the first column of the first row of the first table
}
}
Note: I've wrapped both examples in the C# using statement, this ensures that all your database resources are cleaned up so you don't have any problems with with leaking unmanaged resources. It's not particularly difficult or complicated so is well worth doing

I think, in this case, you'd be better off (performance-wise) to use a SqlCommand instead of the adapter and dataset, and invoke the ExecuteScalar method.
See http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
If you must use the data set, however, ds.Tables[0].Rows[0]["total_amount"] should retrieve your value. You will probably need to type cast the value, though.

Related

Adding Parameters to Command Vs Adapter

I'm curious if there is a difference, if any between adding Parameters to the OracleCommand and then adding them to the OracleDataAdapter or by directly adding them to the OracleDataAdapter?
For example,
Adding them to the OracleCommand and then linking them to the OracleDataAdpater
string f= "foo";
string sql = "SELECT #c FROM Dual";
using(OracleCommand command = new OracleCommand(sql, this.Connection))
{
OracleParameter param = new OracleParameter("#c", f);
command.Parameters.Add(param);
OracleDataAdapter adapter = new OracleDataAdapter(command);
adapter.SelectCommand = command;
DataSet dataset = new DataSet();
adapter.Fill(dataset);
return dataset;
}
Adding them directly to the OracleDataAdapter
string f= "foo";
string sql = "SELECT #c CalcVarValue FROM Dual";
using(OracleCommand command = new OracleCommand(sql, this.Connection))
{
OracleDataAdapter adapter = new OracleDataAdapter(command);
adapter.SelectCommand.Parameters.Add(new OracleParameter("#c", f));
DataSet dataset = new DataSet();
adapter.Fill(dataset);
return dataset;
}
Is one way more preferred over the other? Is adding to the OracleDataAdapter directly faster in execution compared to the other method?
There is no difference whatsoever. In both cases, the parameter is added to the OracleCommand.
Choosing between these two coding styles is a matter of personal preference, coding conventions you are obligated to (if exists) and mostly, opinion.
Personally, I tend to go with the shortest possible code that you can still read a year from the day you wrote it and understand what it does without having to think about it, or as someone once wrote (I think it was on Meta.SE) - In this industry, you should write your code as simple as possible, because the person that will take over the project after you will most likely be an idiot.

Dataset from database is empty

I'm accessing a table from my database. I have added the tables as a dataset in Visual Studio 2013, but when I try to use it, it comes out empty.
This is what I'm trying to do:
IQueryable<NorthwindDataSet.OrdersRow> LookupOrdersForYear(int year)
{
using (var context = new NorthwindDataSet())
{
var orders =
from order in context.Orders
where order.OrderDate != null && order.OrderDate.Year >= year
select order;
return orders.ToList().AsQueryable();
}
}
I found out that orders was empty, so I added
Console.WriteLine(context.Orders.Count);
which gave me an output of 0. What went wrong?
I found out that I needed to fill my dataset with data, or it would stay empty.
A SqlDataAdapter did the trick:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand("SELECT * FROM Orders");
string connString = #"Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
adapter.SelectCommand = command;
adapter.SelectCommand.Connection = conn;
adapter.Fill(context.Orders);
There are several overloaded methods for SqlDataAdapter.Fill, of which one takes a dataset and another takes a datatable. When I first used the SqlDataAdapter, I used the one that takes a dataset
adapter.Fill(context);
which still gave me an empty context.Orders. The correct one takes a datatable:
adapter.Fill(context.Orders);
This one worked and returned the dates as expected.

Transaction handling in dataset based insert/update

I am trying to insert bulk records in a sql server database table using dataset. But i am unable to do transaction handling. Please help me to apply transaction handling in below code.
I am using adapter.UpdateCommand.Transaction = trans; but this line give me an error of Object reference not set to an instance of an object.
Code:
string ConnectionString = "server=localhost\\sqlexpress;database=WindowsApp;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlTransaction trans = conn.BeginTransaction(IsolationLevel.Serializable);
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Test ORDER BY Id", conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.UpdateCommand.Transaction = trans;
// Create a dataset object
DataSet ds = new DataSet("TestSet");
adapter.Fill(ds, "Test");
// Create a data table object and add a new row
DataTable TestTable = ds.Tables["Test"];
for (int i=1;i<=50;i++)
{
DataRow row = TestTable.NewRow();
row["Id"] = i;
TestTable .Rows.Add(row);
}
// Update data adapter
adapter.Update(ds, "Test");
trans.Commit();
conn.Close();
If the data-adapter doesn't make it easy to pass in a transaction, and doesn't handle it internally, then you might be able to force it by using TransactionScope instead - since this is ambient rather than explicit.
However! My main guidance here would be more simple: stop using data-sets and data-adapters. They were essentially hangover from pre-.NET patterns, and were handy when the data tooling for .NET was in an early state. It is no longer in that state. Virtually any other data access tool would be preferable.
I could not test your code, but I think you should also pass the connection of the trans object to your adapter like in the following example:
...
adapter.UpdateCommand.Connection = trans.Connection;
adapter.UpdateCommand.Transaction = trans;
...
Good luck!
Source: CodeProject

c# cant insert row but can select

c# developers, can you say what wrong in that simple code?
public SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["WpfApplication.Properties.Settings.BRDSConnectionString"].ToString());
public DataTable dt;
private void FillDataGrid()
{
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["WpfApplication.Properties.Settings.BRDSConnectionString"].ToString());
SqlCommand comm = new SqlCommand("select * from B_RDS_DIST",con);
SqlDataAdapter da = new SqlDataAdapter(comm);
dt = new DataTable();
da.Fill(dt);
CBDist.ItemsSource = dt.DefaultView;
CBDist.DisplayMemberPath = "NAM";
CBDist.SelectedValuePath = "KEY";
try
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO B_RDS_DIST (NAM) VALUES (#NAM)", con);
cmd.Parameters.Add("#NAM", SqlDbType.VarChar, 255).Value="sadName";
da.InsertCommand = cmd;
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I can select, but can't insert. No exeptions here.
Table has only two columns KEY (PK,AI) and NAM (varchar 255).
May be I need to do something with connection to allow insert, or I missed something?
Thanks.
added
almost forgot, i use mdf file, so connectionString looks like:
"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\BRDS.mdf;Integrated Security=True"
ANSWER - copy-paste pleas, i have no rputation.
Oh god, that was so dramatical old problem with generated Connection string!
Old connection string:
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\BRDS.mdf;Integrated Security=True"
New connection string:
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Im awsome\Documents\Visual Studio 2013\Projects\WpfApplication\WpfApplication\BRDS.mdf;Integrated Security=True"
Insert/Delete/Update works well.
I have only two "simple for you" questions now:
1) How can i use dataTable to update simple table in database. Do i need create data table with one column "NAM"?
2) Why is so hard to detect this damn simple problem with connection string!? :D
If this is how you want to do this....
Edited:
SqlDataAdapter lcDataAdapter = new SqlDataAdapter()
lcDataAdapter.InsertCommand = new SqlCommand("INSERT INTO B_RDS_DIST (NAM) VALUES (#NAM)", con);
lcDataAdapter.InsertCommand.Parameters.Add("#NAM", SqlDbType.VarChar, 255).Value="sadName";
lcDataAdapter.InsertCommand.ExecuteNonQuery();
Note: I would not use the InsertCommand method on the data adapter for inserting records, but this is a case of developer preference. The above should work for you though as-is.
That is not how you use DataAdapters, you need to call da.Update(dt) to invoke any Insert, Update, or Delete queries that need to be performed on the DataTable to reflect any changes you made to the original DataTable.
Either totally seperate out your insert command from the data adapter or add the row to the data table you populated from Fill(dt) and don't use separate connecting strings (it would actually be better to not write your own insert at all and use SqlCommandBuilder and just do da.InsertCommand = cmdBuilder.GetInsertCommand(); and it will automaticly build the insert based off of the Select you passed in to the DataAdapter)

C# Fill combo box from SQL DataTable

DataTable _dt = new DataTable();
using (SqlConnection _cs = new SqlConnection("Data Source=COMNAME; Initial Catalog=DATABASE; Integrated Security=True"))
{
string _query = "SELECT * FROM Doctor";
SqlCommand _cmd = new SqlCommand(_query, _cs);
using (SqlDataAdapter _da = new SqlDataAdapter(_cmd))
{
_da.Fill(_dt);
}
}
cbDoctor.DataSource = _dt;
foreach(DataRow _dr in _dt.Rows)
{
cbDoctor.Items.Add(_dr["name"].ToString());
}
There was an Error...
The result is System.Data.DataRowView instead of data from database..
I'm not yet sure what is the exact error in your code, but if you're ok with not using DataTable, you can do it this way:
using (SqlConnection sqlConnection = new SqlConnection("connstring"))
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM Doctor", sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
cbDoctor.Items.Add(sqlReader["name"].ToString());
}
sqlReader.Close();
}
For more information take a look at SqlDataReader reference on MSDN.
In orer to find the issue in the original code you posted, please provide information in which line you get the exception (or is it an error that prevents application from compiling?) and what is its whole message.
You could also specify DisplayMember property of combobox to any of the column name.
For example if you want to display Name field, you could do
Combobox1.DisplayMember="Name";
I think the problem is that you are trying to insert multiple columns into a comboBox (which can accept only one column). Adjust your SELECT statement so that it combines all of the data you need into one column:
Example:
SELECT Name + ' ' LastName + ' '+ ID AS 'DoctorData' FROM Doctor
By using the + operator you can combine multiple columns from the database, and represent it as a single piece of data. I think that your code should work after that (you can even comment the foreach loop, I think that adding data source to your comboBox will be enough)

Categories