SQL Query Selecting data from a specific time period - c#

So im trying to select students, rooms and so on from a specific time period which is between 01-01-2020 and 30_06-2020. I tried googleing to see if i could find the answer but it seems tricky to just find something that will work for my instance
public static List<Student_Room> GetFirstSemesterStudents(int id)
{
List<Student_Room> studentRoomList = new List<Student_Room>();
string query = $"select Leasing.Student_No, Leasing.Room_No, Student.Name, Leasing.Date_From, Leasing.Date_To from Leasing,Student where Leasing.Date_from = '01012020' AND Leasing.Date_To = '30062020' AND Dormitory_No = #id";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#id", id);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Student_Room studentRoom = new Student_Room();
studentRoom.Student_No = Convert.ToInt32(reader["Student_No"]);
studentRoom.Student_Name = Convert.ToString(reader["Name"]);
studentRoom.Room_No = Convert.ToInt32(reader["Room_No"]);
studentRoom.Date_From = Convert.ToDateTime(reader["Date_From"]);
studentRoom.Date_To = Convert.ToDateTime(reader["Date_To"]);
studentRoomList.Add(studentRoom);
}
return studentRoomList;
}
}
}
The main problem is just that i dont know how to write the query, ther rest should be correct. i get the "Conversion failed when converting date and/or time from character string" when i try to run the function on the site
We just started learning about this stuff so im still not the best at queries and dont know much, thank for looking at it and helping appriciate it :D

make sure in database you have to define the datatype for date as the same in the Student_Room class, either date alone or datetime , if you want to chage to date alone as it is defined in the class the you can use
studentRoom.Date_From = DateTime.Parse(reader["Date_From"]);
studentRoom.Date_To = DateTime.Parse(reader["Date_To"]);

Related

Using OleDDataReader to pull specific data from a database using a SQL command, C#

I am working on a project, where I want to use a SQL command string to sort through my database in ascending order according to one of the columns and then use another command to get the first value that is greater than or equal to a measured value.
For some reason or another my code only prints out 1, no matter what I change the value that is being measured against the database to. I'm not sure if there is an issue with my second SQL command string or if I am messing up with the OleDb Get methods.
I am a bit rusty with my programing so, additional advice would be appreciated.
Here is my code:
bool renew;
string conn = TableSettings.Instance.GetConnectionString();
string readingInDoubles = lblReading.Text;
double dNumber;
renew = Double.TryParse(readingInDoubles, out dNumber);
string SqlCmdSort = "SELECT * FROM Tables ORDER BY Mass ASC";
string SqlCmdCompare = "SELECT * FROM Tabels WHERE Mass >= " + renew;
using (OleDbConnection connect = new OleDbConnection(conn))
{
OleDbCommand command = new OleDbCommand(SqlCmdSort, connect);
OleDbCommand command2 = new OleDbCommand(SqlCmdCompare, connect);
connect.Open();
OleDbDataReader sort = command.ExecuteReader();
while (sort.Read())
{
OleDbDataReader compare = command2.ExecuteReader();
compare.Read();
// compare.GetDouble(0); ignore this.
lblUpperValue.Text = compare[0].ToString();
compare.Close();
}
sort.Close();
connect.Close();
}

Need to select a value from table and store it into variable

Hello everyone I am currently working on some testing project and I am having a little problem. Using selenium, I need to SendKey in specific element but instead of fixed value i need to use value (data) from my database. Can anyone help me with how to retrieve single value from database and store it in a variable so i can use it later.
Thank you and sorry for a noobish question - see code below:
SqlConnection conn = new SqlConnection();
SqlCommand command;
SqlDataReader dataReader;
conn.ConnectionString = "Server=******;Database=****;User ID=sqlserver;password=****;MultipleActiveResultSets=true;");
string query = "select RequestID, from AutomaticPayment where RequestID ='1230322'";
DataTable dt = new DataTable();
command = new SqlCommand(query, conn);
conn.Open();
dataReader = command.ExecuteReader();
dt.Load(dataReader);
driver.FindElement(By.Id("requestID")).SendKeys(VALUE FROM DATABASE);
You can use the following code
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlDataAdapter sda = new SqlDataAdapter(query, connection);
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
try
{
result = cmd.ExecuteScalar().ToString();
}
catch(NullReferenceException n)
{
result = "";
}
}
ExecuteScaler gets you the first column of the first row and additional columns are ignored. Use the value from result in your SendKeys()
Use conditions to limit the result:
Select data
SELECT TOP 1 RequestID FROM AutomaticPayment // Always returns 1 row
Or
SELECT RequestID FROM AutomaticPayment WHERE Id = 123 // Id must be unique to return 1 row
And maybe other ways.
Get value
var value = dt.Rows[0][1];
Or
var value = dt.Rows[0]["RequestID"];
From what i worked on with SqlCommand just do the following :
int yourId = 0;
dataReader = command.ExecuteReader()
while(dataReader.Read())
{
yourId = dataReader.GetInt32(0);
}
With that, you should have your value set to the first column of the dataReader. (that is selected thanks to your query, since you are requesting on a specific id, i guess it will return only one column
there is many other type available for Reader : Reader Microsoft Doc
And if you have in the futur many data to collect, use the ORM entity framework, work well for me
Source
EDIT :
Since you are only querying one data, maybe the solution of #work_ishaan is better than mine in this case, check it out.

How to hold a SQL SUM() query int a Variable

Good day.
I have an SQL query in C# as shown.
using (SQLiteConnection con = new SQLiteConnection(Connection.DatabaseLocationString))
{
SQLiteCommand cmd = null;
string query =
String.Format("SELECT MONTH(SaleDate) month,
SUM(AmountPaid) sum_amountpaid
FROM {0}
WHERE YEAR(SaleDate) = #1
GROUP BY MONTH(SaleDate) ", Sale.TABLE_NAME);
cmd = new SQLiteCommand(query, con);
cmd.Parameters.Add(
new SQLiteParameter("#1", Properties.Settings.Default.ChartYearlyDisplay));
con.Open();
SQLiteDataReader reader = cmd.ExecuteReader();
con.Close();
}
My challenge is, i have never done nor used a query like this. But what i want to achieve is, i want too Get the value of SUM(AmountPaid) for each month, like this.
January = 20000.00
Febuary = 18000.00
March = 10000.00
.......and so on.
But i really dont know how too come of that.
please i need your help, Thanks.
You just need to loop over the returned results using the SQLiteDataReader
SQLiteDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Console.WriteLine(reader["month"].ToString());
Console.WriteLine(reader["sum_amountpaid"].ToString());
}
con.Close();
Of course, if you need to return this data, you need a data structure where you can store the results like a List<T>
// The class where you keep the value for a single month...
public class MonthAmount
{
public int Month {get;set;}
public decimal Amount {get;set;}
}
....
// A List where each month of data will be added...
List<MonthAmount> amountData = new List<MonthAmount>();
while(reader.Read())
{
// Create the instance of MonthAmount for the current month..
MonthAmount m = new MonthAmount()
{
Month = Convert.ToInt32(reader["month"]);
Amount = Convert.ToDecimal(reader["sum_amountpaid"]);
}
// Add it to the list...
amountData.Add(m);
}
reader.Close();
// Return the info to the caller....
return amountData;
Also according to SQLite docs, there is no MONTH or YEAR functions available, you should use strftime with an appropriate settings. You could try with
string query = $"SELECT strftime('%', SaleDate) month,
SUM(AmountPaid) sum_amountpaid
FROM {Sale.TABLE_NAME}
WHERE strftime('%Y', SaleDate) = #1
GROUP BY strftime('%m', SaleDate)";
And if I am not wrong, the result of this strftime function is a string not an integer (IE '03' for March, '2017' for year) so perhaps you should create a parameter with the correct datatype.

How can I use TableDirect for SQL Server CE?

I have code that works for querying data from a SQL Server CE table and populating a generic list with it. That can be seen here:
But a comment there indicates I should trade in my horse-and-buggy for a Leer Jet; so, I'm trying to adapt code I found here and have this so far:
public static List<HHSUtils.InventoryItem> SelectLocalInventoryItemsTableDirect()
{
var invItems = new List<HHSUtils.InventoryItem>();
using (var conn = new SqlCeConnection(dataSource))
{
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.TableDirect;
cmd.CommandText = "InventoryItems";
using (SqlCeResultSet rs cmd.ExecuteResultSet(ResultSetOptions.Scrollable))
{
cmd.Prepare();
while (rs.Read())
{
var invItem = new HHSUtils.InventoryItem
{
Id = Convert.ToString(rs["Id"]),
PackSize = Convert.ToInt16(rs["PackSize"]),
Description = Convert.ToString(rs["Description"]),
DeptDotSubdept = Convert.ToDouble(rs["DeptDotSubdept"]),
Unit_Cost = Convert.ToDouble(rs["UnitCost"]),
Unit_List = Convert.ToDouble(rs["UnitList"]),
UPC_code = Convert.ToString(rs["UPCCode"]),
UPC_pack_size = Convert.ToInt16(rs["UPCPackSize"]),
CRV_Id = Convert.ToInt32(rs["CRVId"])
};
invItems.Add(invItem);
}
}
}
return invItems;
}
...but since I'm simply looping through the result set to populate the generic list, I reckon I don't want ResultSetOptions.Updatable (and I'll need different code following that). Of the following possibilities:
Insensitive
None
Scrollable
Sensitive
Updatable
...which is best for my situation - Scrollable?
UPDATE
This seems to work fine, and fast, but I still don't know which ResultSetOptions property is optimal...This msdn article talks about this enumeration, but doesn't exactly go into great depth about when they should/not be used.
You'd want to use None in your case. cmd.Prepare is also unnecessary. As indicated in this question, GetValues is also faster.

asp.net C# database table column to list

I have an asp.net project done in C# (my C# syntax is very rusty) and am using the built in database it creates with the project. I've created a table called aspnet_Tutorials that (for now) stores two columns of user submitted data: TutorialName and TutorialContent. Very simple, it's a learning project.
What I need to do is create a list from the first column of aspnet_Tutorials to use it to create a "directory" of the tutorials on a page. The part I'm having trouble with, mostly syntactically, is connecting to and iterating over the column to get the values into a list. Could anyone provide a straight forward example of this? And possibly explain what's going on in the code.
public class TutorialsDirDAL
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
public List<string> DisplayTutorials() //parameters? String qry?
{
//query the database table, foreach loop over the data, place it into a list?
}
}
I know how to write simple sql queries. But I've seen a couple different set ups for this in my Googling spree. I currently have the following for a query, feel free to pick it apart or offer a better solution than using a query.
cmd.CommandText = "SELECT * FROM ASPNET_TUTORIALS (TutorialTitle)"
+ "VALUES (#tutorialTitle)";
Thank you!
ebad86's answer is acceptable but since you are obviously learning I think introducing OO principals muddy the water with what you are trying to learn at this point.
Here is a basic method:
private void GetData()
{
//The object that will physically connect to the database
using(SqlConnection cnx = new SqlConnection("<your connection string>")
{
//The SQL you want to execute
SqlCommand cmd = new SqlCommand("SELECT * FROM ASPNET_TUTORIALS");
//Open the connection to the database
cnx.Open();
//execute your command
using (IDataReader dataReader = cnx.ExecuteReader(cmd))
{
//Loop through your results
while(dataReader.Read())
{
//do whatever to the data
ListItem item = new ListItem(Convert.ToString(dataReader["TutorialName"]));
lst.Items.Add(item);
}
}
}
}
This is all very straightforward. The part you are most interested in is the while loop though. The loop will go through all of the returned records and you can do whatever you need to do with them. In my example I have assumed that there is a ListBox named 'lst' and I am simply adding ListItems to it that will have the name of whatever 'TutorialName' is. You can make literally do whatever you need to do with the data at this point. To fit your example (returning a List) you would do this:
private List<string> GetData()
{
List<string> lst = new List<string>();
//The object that will physically connect to the database
using(SqlConnection cnx = new SqlConnection("<your connection string>")
{
//The SQL you want to execute
SqlCommand cmd = new SqlCommand("SELECT * FROM ASPNET_TUTORIALS");
//Open the connection to the database
cnx.Open();
//execute your command
using (IDataReader dataReader = cnx.ExecuteReader(cmd))
{
//Loop through your results
while(dataReader.Read())
{
lst.Add(Convert.ToString(dataReader["TutorialName"]));
}
}
}
return lst;
}
Please respond if you have any questions.
Well you can fetch using data reader and map to the object. I can give you some rough code, which could be like this:
using (IDataReader objDataReader = objDB.ExecuteReader(objCMD))
{
while (objDataReader.Read())
{
DataBaseObject obj = new DataBaseObject();
obj = MapObjectToList(objDataReader);
ObjectList.Add(obj);
}
objDataReader.Dispose();
}
// Mapping Function can be called somewhat like this:
private DataBaseObject MapObjectToList(IDataReader objDataReader)
{
DataBaseObject obj = new DataBaseObject();
obj.Prop1Name = base.GetDataValue<string>(objDataReader, "Column1Name");
obj.Prop2Name = base.GetDataValue<string>(objDataReader, "Column2Name");
return obj;
}
But this is just a rough idea how I would do it.

Categories

Resources