I have to find max value of one table using dataset.
I have written code for that as follows :
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select max(FlightBookingID) from dbo.FlightBookingDetails", FlyCon);
da.Fill(ds);
if (ds != null)
{
Session["FBookingID"] = Convert.ToString(ds.Tables[0].Rows[0]["FlightBookingID"]);
}
But its geting error in
Convert.ToString(ds.Tables[0].Rows[0]["FlightBookingID"]);
What changes should i do in above code?
Why can't you use SqlCommand.ExecuteScalar?
using (SqlCommand comm = new SqlCommand("select max(FlightBookingID) from dbo.FlightBookingDetails", FlyCon))
{
var result = comm.ExecuteScalar();
if (!Convert.IsDBNull(result))
Session["FBookingID"] = result;
}
DataSet is very complex class, and you shouldn't create it just to get one value from the database.
ds.Tables[0].Rows[0].Item["FlightBookingID"].toString();
You are getting String directly here
Try this.
Session["FBookingID"] = ds.Tables[0].Rows[0]["FlightBookingID"].ToString();
I think you should use Alias on your query :
SqlDataAdapter da = new SqlDataAdapter("select max(FlightBookingID) as FlightBookingID from dbo.FlightBookingDetails", FlyCon)
and so you can acces the column by name. Otherwise you can access it by column index :
Session["FBookingID"] = Convert.ToString(ds.Tables[0].Rows[0][0]);
Related
I've a SQL query which tries to fetch all records that were created within the last one hour
string query = "select * from Monarchchangelog mcl WHERE LOWER(mcl.mcl_usercomment) LIKE 'bolt%' AND mcl.mcl_createtime > DATEADD(MINUTE, -#minutesBack, GETDATE()) ORDER BY mcl.mcl_createtime DESC";
string tablename = "NEW_UPDATES";
string minutesBack = "60"; //set by another function but for eg sake I've hardcoded the value
SqlCommand command = new SqlCommand(query);
command.Parameters.AddWithValue("minutesBack", minutesBack);
DataSet ds = RunQuery(command, tablename);
which I'm executing with the below code
private DataSet RunQuery(SqlCommand command, String tablename)
{
DataSet ds = null;
SqlDataAdapter adapter = null;
using (SqlConnection oc = new SqlConnection(CONNECTIONSTRING))
{
try
{
oc.Open();
command.CommandType = CommandType.Text;
command.Connection = oc;
adapter = new SqlDataAdapter(command);
ds = new DataSet();
adapter.Fill(ds, tablename);
}
catch
{
if (ds != null)
{
ds.Dispose();
}
}
finally
{
if (oc != null)
{
oc.Close();
oc.Dispose();
}
}
}
return ds;
}
when I try to execute this code I'm getting the below error but mcl_createtime is of datetime datatype
operand data type nvarchar is invalid for minus operator
Can someone let me know where am I going wrong
Thank you
With the help of #DaleK's comment I resolved the issue, replaced the code
command.Parameters.AddWithValue("minutesBack", minutesBack);
with this piece
command.Parameters.Add("minutesBack", SqlDbType.Int).Value = minutesBack;
A good way of passing your parameters is by explicitly mentioning the sql datatype to avoid datatype issues like this. For more details please follow the link AddWithValue vs Add.
So I passed my parameter as a number and not a string, also got a good understanding of try-catch, using statements.
Good learning, thank you everyone for your contribution.
I have a dataset called "dts_Material_Report" which is used to generate reports.In that data set I have a tableAdapter called "dt_report_Received_Materials".
Previously I have load the data to that table adapter with following code ,
private void generate_report( string qry )
{
string query, qry1;
query = qry;
int pr_id = Form_Common_PCM.pr_id;
clz_Common_SqlConnection con = new clz_Common_SqlConnection();
SqlDataAdapter sda = new SqlDataAdapter(query, con.ActiveCon());
DataSet dts = new DataSet();
sda.Fill(dts, "dt_report_Received_Materials");
rdc.SetDataSource(dts);
crystalReportViewer1.ReportSource = rdc;
crystalReportViewer1.DisplayToolbar = true;
crystalReportViewer1.Show();
}
But currently I am having all the data which I need to generate the report in one of my data table called "dt_mat_cost".
int Ref_ID_s_category;
Ref_ID_s_category = Convert.ToInt16(cbo_sub_category .SelectedValue );
int pro_id = Form_Common_PCM.pr_id;
clz_Received_Material_Summary rms = new clz_Received_Material_Summary();
DataTable dt_mat_cost = rms.Summary_Material_Cost_Filter_By_Project_By_Sub_Category(Ref_ID_s_category);
Now i want to load those data from "dt_mat_cost" to my tableAdapter "dt_report_Received_Materials" .Is there any way to do this.
Thanks in Advance.
One way to resolve this would be to put the DataTable into a DataSet and then run the crystal code as shown below. You may be able to just set the ReportSource to the datatable but I do not recall off the top of my head if that will work.
DataTable dt_matCost = rms.Summary_Material_Cost_Filter_By_Project_By_Sub_Category(Ref_ID_s_category);
DataSet dts = new DataSet();
dts.Tables.Add(dt_matCost);
//ds.Tables[0].TableName = "Whatever CR thinks it is"; // may need to set for CR
rdc.SetDataSource(dts);
crystalReportViewer1.ReportSource = rdc;
crystalReportViewer1.DisplayToolbar = true;
crystalReportViewer1.Show();
I have this code
SqlConnection conn = Database.GetConnection();
//not sure why doing this bit (bit between this comment and next
//SqlDataAdapter adapter = new SqlDataAdapter("Select * From CarType", conn);
DataSet DataSetRentals2 = new DataSet("CustomerSQLTable");
DataTable table = new DataTable("CustomerSQLTable"); //you can name it
DataTable table2 = new DataTable("CarRental");
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = new SqlCommand("SELECT * FROM Customer", conn);
conn.Open();
///this might brake the code
///
adapter.Fill(DataSetRentals2,"CustomerSQLTable");
adapter.SelectCommand = new SqlCommand("SELECT * FROM CarRental", conn);
adapter.Fill(DataSetRentals2, "CarRental");
adapter.Fill(DataSetRentals2, "CarRental");
}
CustomerGrid.DataSource = DataSetRentals2;
CustomerGrid.DataMember = "CustomerSQLTable";
CarRGrid.DataSource = DataSetRentals2.Tables["CarRental"];
CarRGrid.DataMember = "CarRental";
the teacher gave me this code to link them in a relationship so that when i click on one customer number in one data grid and for it to only return corresponding records in the other.
DataRowView selectedRow =
(DataRowView)CustomerGrid.SelectedRows[0].DataBoundItem;
DataSetRentals2.Tables["CarRental"].DefaultView.RowFilter =
"CustomerNo = " + selectedRow.Row["CustomerNo"].ToString();.
so what i think i need to do is to name the columns in the dataset. But i have no idea how to do this. I'm sure there must be a way an I'm sure you guy's can easily tell me it. Thank you in advanced.
dataTable.Columns[0].ColumnName = "MyColumnName";
Your columns will already have names. They are supplied by the database.
I would guess that your issue is with this line. If this isn't it please describe what you're expecting to happen, vs what is actually happening so that we may assist you better.
CarRGrid.DataSource = DataSetRentals2.Tables["CarRental"];
Which should probably be
CarRGrid.DataSource = DataSetRentals2;
I need to get retrive all of the data from specified tables and I don't need the data to be strongly typed so I am returning it as a data table.
public DataTable GetByTypeName(String t)
{
var type = Type.GetType(t);
var dt = new DataTable();
using (var sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["MasterPlanConnectionString"].ConnectionString))
{
var sqlComm = new SqlCommand("SELECT * FROM #table", sqlConn);
sqlComm.Parameters.AddWithValue("#table", type.Name);
sqlConn.Open();
var dr = sqlComm.ExecuteReader(CommandBehavior.CloseConnection);
dt.Load(dr);
}
return dt;
}
When I run this I get the error
System.Data.SqlClient.SqlException was unhandled by user code
Message=Must declare the table variable "#table".
I cannot figure out why this isn't working as I have declared #table. I know this method is open to some bad sql attacks so I plan to add in some protection about exactly what types can be queried against.
You can construct your query dynamically - (should be ok over here, but may expose your query to sql injection)
var query = String.Fromat("Select * from [{0}]", type.Name);
var sqlComm = new SqlCommand(query, sqlConn);
/*sqlComm.Parameters.AddWithValue("#table", type.Name);*/
I need to write a program. A part of the program is to write to an sql database (.mdf).
I had a lot of trouble trying to add a new row to my table (called: "Data"). Here is the code:
...
DataSet ds = new DataSet();
System.Data.SqlClient.SqlDataAdapter da;
DataRow dRow;
string sql = "SELECT * From Data";
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
...
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
dRow = ds.Tables["Data"].NewRow();
dRow[0] = "my_data1";
dRow[1] = "my_data2";
dRow[2] = "my_data3";
...
ds.Tables["Data"].Rows.Add(dRow);
da.Update(ds, "Data");
...
I execute this code, but the data didn't get saved to the table. Does anyone know how to enter a new row to the table and to save it?
You need an InsertCommand in your SqlDataAdapter.
EDIT:
Here's a quick example I whipped up. There are many others out there, but this should get you going. It assumes that you have a table (dbo.Foos) with two columns (Foo int, Bar nvarchar(50)).
namespace DataAdapterSample
{
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main(string[] args)
{
using (SqlConnection connection = new SqlConnection(#"Data Source=[your server];Initial Catalog=[your database];Integrated Security=true;"))
{
using (SqlDataAdapter dataAdapter = new SqlDataAdapter())
{
dataAdapter.SelectCommand = new SqlCommand("select Foo, Bar from dbo.Foos", connection);
dataAdapter.InsertCommand = new SqlCommand("insert into dbo.Foos (Foo, Bar) values (#Foo, #Bar)", connection);
dataAdapter.InsertCommand.Parameters.Add(new SqlParameter("Foo", SqlDbType.Int, 4, "Foo"));
dataAdapter.InsertCommand.Parameters.Add(new SqlParameter("Bar", SqlDbType.NText, 50, "Bar"));
using (DataSet dataSet = new DataSet())
{
dataAdapter.Fill(dataSet);
Console.WriteLine("There are {0} rows in the table", dataSet.Tables[0].Rows.Count);
DataRow newRow = dataSet.Tables[0].NewRow();
newRow["Foo"] = 5;
newRow["Bar"] = "Hello World!";
dataSet.Tables[0].Rows.Add(newRow);
dataAdapter.Update(dataSet);
}
//Just to prove we inserted
using (DataSet newDataSet = new DataSet())
{
dataAdapter.Fill(newDataSet);
Console.WriteLine("There are {0} rows in the table", newDataSet.Tables[0].Rows.Count);
}
}
}
Console.ReadLine();
}
}
}
Force the dataset to Accept changes ie add ds.Acceptchanges to your code
Two things I'm seeing, you're not initializing your Dataset (ds) or SqlDataAdapter (da) in anyway (unless you're simply leaving that out for post simplification). Part of the initialization of the da will be giving it an actual sql command.
Try instead to set
dRow = new DataRow();
instead of
dRow = ds.Tables["Data"].NewRow();
and change
da.Update(ds, "Data");
to
da.Update(ds);