Create list from sqlite database join function - c#

I'm trying to make a list from a sqlite database join. I'd like to get the date values when the specific machine is selected. Example: Machine A is selected, it makes a list of 05/25/15, 05/30/15, 05/20/15. With the join I'm using it wants to spit out the column name but not the values. It's an ambiguous column error with sqlite.
void fill_listbox_Dates()
{
string Machine_Name_listbox = listboxMachines.SelectedItem.ToString();
string databaseString = "datasource=LinacDatabase.db";
string DateQuery = "SELECT Date FROM Machines as E1 INNER JOIN Date as E2 ON Machines.Machine= " + Machine_Name_listbox + "";
SQLiteConnection conDatabase = new SQLiteConnection(databaseString);
SQLiteCommand cmdDataBase = new SQLiteCommand(DateQuery, conDatabase);
SQLiteDataReader ReadDate;
try
{
conDatabase.Open();
ReadDate = cmdDataBase.ExecuteReader();
while (ReadDate.Read())
{
List<string> Dates = ReadDate.GetString(1);
listboxDates.Items.Add(Dates);
}
}

So the problem was that I had to insert a single quote value around to double quote of the Machine_Name_List box string. Otherwise the sqlite datareader will think the value is a column name. So it should read,
string DateQuery = "SELECT Date FROM Machines as E1 INNER JOIN Date as E2 ON Machines.Machine= '" + Machine_Name_listbox + "'";

Related

How to use two queries to find result on the basis of first query

I have two tables Repair_master and New_Equipment_info, with the query shown here, I am able to retrieve all the latest date record of maint. by grouping RID and fill the data grid.
SELECT
t1.RID
,t1.RDATE
,t1.EQ_ID
,new_equipment_info.Equipment_Name
,new_equipment_info.Complete_specification
,t1.DEPT
,t1.REPAIR_MAINT
,t1.ACTION_TAKEN
,t1.SAPRES
,t1.ATT_BY
,t1.[STATUS]
,t1.RNO
FROM
Equipment.dbo.REPAIR_MASTER t1
INNER JOIN
Equipment.dbo.new_EQUIPMENT_INFO
ON t1.EQ_ID = New_Equipment_info.Equipment_Id
INNER JOIN
(
SELECT
Eq_ID
,max(RDate) as MaxDate
FROM
Equipment.dbo.REPAIR_MASTER
group by
Eq_ID
) tm
ON t1.EQ_ID = tm.EQ_ID
and t1.RDATE = tm.MaxDate
WHERE
t1.Repair_Maint = 'maint.'
ORDER BY
t1.RDATE DESC
But I want to know the number of days from the last date filtered from query and current date.
Like this
DATEDIFF(day, MaxDate, GETDATE()) AS Difference)
Kindly advise
Further I want to enter number of days in text box and click button and show only those records having a difference greater than the value entered.
private void btnOverDue_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(connString))
{
string p = "SELECT t1.[RID],t1.[RDATE],t1.[EQ_ID],new_equipment_info.Equipment_Name,new_equipment_info.Complete_specification," +
"t1.[DEPT],t1.[REPAIR_MAINT],t1.[ACTION_TAKEN],t1.[SAPRES],t1.[ATT_BY],t1.[STATUS],t1.[RNO]FROM([Equipment].[dbo].[REPAIR_MASTER] t1 inner join[Equipment].[dbo].new_EQUIPMENT_INFO ON " +
"t1.EQ_ID = New_Equipment_info.Equipment_Id inner join (select Eq_ID, max(RDate) as MaxDate FROM [Equipment].[dbo].[REPAIR_MASTER] group by Eq_ID) tm on t1.EQ_ID=tm.EQ_ID and t1.RDATE =tm.MaxDate)" +
"where t1.Repair_Maint='maint.' ORDER BY t1.RDATE desc";
SqlCommand cmd = new SqlCommand(p, con);
SqlDataAdapter dataadapter = new SqlDataAdapter(p, con);
DataSet ds = new DataSet();
dataadapter.Fill(ds, "Repair_master");
EquipGrid.DataSource = ds;
EquipGrid.DataMember = "Repair_master";
}
}

SQL query to format date datatype to exclude time [duplicate]

This question already has answers here:
how to remove time from datetime
(10 answers)
Closed 4 years ago.
I'm trying to fill a listbox with dates from an SQL database when an account transaction is selected in another listbox. Right now the dates are displaying times as well as dates. I'm using a date datatype in my Date data table but i'm not sure how to format the date to exclude time.
try
{
string query = "select a.Date from Date a inner join AccountTransaction act on" +
" a.Id = act.DateId where act.AccountId = #AccountId";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
using (sqlDataAdapter)
{
sqlCommand.Parameters.AddWithValue("#AccountId", AccountList.SelectedValue);
DataTable associatedDateTable = new DataTable();
sqlDataAdapter.Fill(associatedDateTable);
DateList.DisplayMemberPath = "Date";
DateList.SelectedValuePath = "Id";
DateList.ItemsSource = associatedDateTable.DefaultView;
}
}
catch (Exception e)
{
// MessageBox.Show(e.ToString());
}
DateTime is not having a format. It's just a date. If you want to show it in a specific way, you have to convert it.
select getdate()
gives you: 2019-01-23 12:51:03.663
select CONVERT (varchar(10), getdate(), 103) AS [DD/MM/YYYY]
gives you 23/01/2019
string query = "select CONVERT (varchar(10), a.Date, 103) AS [DD/MM/YYYY] from Date a inner join AccountTransaction act on" +
" a.Id = act.DateId where act.AccountId = #AccountId";

Filter data from DB with datetimepicker

I have two columns with date_of_delivery and date_of_receipt. I want to filter my data
private void button25_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
if(radioButton9.Checked)
{
if ((Convert.ToDateTime(dateTimePicker3.Value)) <= (Convert.ToDateTime(dateTimePicker4.Value)))
{
try
{
string query = "SELECT work_id, surname, first_name, patronymic, type_of_service.name_type_of_service, date_of_receipt, date_of_delivery, car_model.name_model, price_for_work FROM mechanic INNER JOIN work ON work.mechanic_id = mechanic.mechanic_id INNER JOIN type_of_service ON work.type_of_service_id = type_of_service.type_of_service_id INNER JOIN car ON work.car_id = car.car_id INNER JOIN car_model ON car.car_model_id = car_model.car_model_id WHERE work.date_of_receipt >= '" + Convert.ToDateTime(dateTimePicker3.Value) + "' AND work.date_of_delivery <= '" + Convert.ToDateTime(dateTimePicker4.Value) + "'";
MessageBox.Show("" + query);
dataGridView2.DataSource = query;
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.Fill(ds, query);
dataGridView2.DataSource = ds.Tables[query];
}
catch (Exception e2)
{
MessageBox.Show(e2.Message);
}
}
else
{
MessageBox.Show("Дата начала ремонта не может быть позже его завершения ");
}
}
else if(radioButton10.Checked)
{
string query = "SELECT work_id, surname, first_name, patronymic, type_of_service.name_type_of_service, date_of_receipt, date_of_delivery, car_model.name_model, price_for_work FROM mechanic INNER JOIN work ON work.mechanic_id = mechanic.mechanic_id INNER JOIN type_of_service ON work.type_of_service_id = type_of_service.type_of_service_id INNER JOIN car ON work.car_id = car.car_id INNER JOIN car_model ON car.car_model_id = car_model.car_model_id WHERE work.price_for_work BETWEEN " + Convert.ToInt32(textBox16.Text) + " AND " + Convert.ToInt32(textBox17.Text) + "";
MessageBox.Show("" + query);
dataGridView2.DataSource = query;
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.Fill(ds, query);
dataGridView2.DataSource = ds.Tables[query];
}
}
However, the data is not sorted. Because the database format of the date 01.02.2015 . How to make sure everything works
As I wrote in the comments, date types does not have a format.
You are sending a string that represents a date value to the database, (the default .ToString() of the DateTime object is called since there is an implicit conversion from date to string when you are concatenating the DateTime to the sql string).
When using strings for a date value in sql it's best to use ANSI-SQL format which is yyyy-MM-dd. This format guarantees that SQL Server will interpret the string as a proper date.
However, concatenating strings to create an SQL statement is a security hazard, since it's an opening for SQL injection attacks.
The proper way is to use parameterized queries or stored procedures.
Replace your query's where clause from this
WHERE work.date_of_receipt >= '" + Convert.ToDateTime(dateTimePicker3.Value) +
"' AND work.date_of_delivery <= '" + Convert.ToDateTime(dateTimePicker4.Value) + "'"
to this:
WHERE work.date_of_receipt >= #date_of_receipt
AND work.date_of_delivery <= #date_of_delivery
Then use the SqlDataAdapter's SelectCommand's Parameters collection to add the values for the parameters:
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.SelectCommand.Parameters.Add("#date_of_receipt ", SqlDbType.Date).Value = dateTimePicker3.Value;
da.SelectCommand.Parameters.Add("#date_of_delivery", SqlDbType.Date).Value = dateTimePicker4.Value;
(Note that the add command returns a reference to the SqlParameter you've just added, therefor you can write the .Value to specify the value of the parameter when adding it to the SelectCommand.
Note that the value of the DateTimePicker is already a DateTime type, so there is no need to use Convert.ToDateTime when adding it.
Do the same thing with all other queries (of course, don't forget to use the proper data types for the parameters).
System.DateTime dt16 = System.DateTime.Parse(textBox16.Text);
string sTextBox16 = dt16.ToString("dd.MM.yyyy");
System.DateTime dt17 = System.DateTime.Parse(textBox17.Text);
string sTextBox17 = dt17.ToString("dd.MM.yyyy");
string query = "SELECT Required Columns WHERE work.date_of_receipt >= "+sTextBox16 +"' AND work.date_of_delivery <= '" + sTextBox17 +"'";

Running SQL Server query using c#

I have the following code :
Connection c = new Connection();
string select1 =
#"SELECT
E.employeeNumber AS 'Employee Number',
E.employeePrivateName + ' ' + E.employeeFamilyName AS 'Employee Name',
DATEDIFF (MONTH, E.startWorkingDate, GETDATE()) AS 'Seniority in Month',
M.machineName AS 'Machine Name', J.jobName AS 'Job Name',
COUNT(E.employeeNumber) AS 'Number of Times on Machine in Specif Job',
SUM(Number_Of_Days_During_The_Period) AS 'Total Working Days on Machine in Specif Job',
SUM(Salary_per_Period) AS 'The Salary For working on Machine in Specif Job'
FROM
TblEmployee E
INNER JOIN
AllSchedules A_S on E.employeeNumber = A_S.employeeNumber
INNER JOIN
TblJob J on J.jobNumber = A_S.jobNumber
INNER JOIN
TblMachine M on M.machineNumber = A_S.machineNumber
INNER JOIN
TblPeriod P on P.Number = A_S.periodNumber
WHERE
Month(P.fromDate) = Month(#Month)
GROUP BY
E.employeeNumber, E.employeePrivateName, E.employeeFamilyName,
E.startWorkingDate, M.machineName, J.jobName
ORDER BY
E.employeeFamilyName , E.employeePrivateName";
SqlCommand cmd = new SqlCommand(select1, c.con);
DateTime month = comboBox1.Text;
cmd.Connection = c.con;
cmd.Parameters.AddWithValue("#Month", month);
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
I want to run the query, however I need to define a datetime value so it would be a search parameter for the query. How do I save the DateTime variable so that it will hold a month number (10 for october, etc.)
Thanks
In your query you have this line for the WHERE condition
WHERE Month(P.fromDate)= Month(#Month)
THe MONTH function of T-SQL expects to receive a Date for its parameter, so you probably need only
DateTime dt = new DateTime(DateTime.Today.Year, month, 1);
and pass this value for the parameter #Month
cmd.Parameters.AddWithValue("#Month", dt);
EDIT: If you have a combobox with items filled with the month names ordered: (January, February....)
// In array the indexes start at zero.....
if(cboMonths.SelectedIndex >= 0)
{
int month = cboMonts.SelectedIndex + 1;
}
You can use
string monthString = DateTime.ParseExact(comboBox1.Text, "MMMM", CultureInfo.CurrentCulture ).Month.ToString("MM");
and to convert it to an integer:
int month = int.Parse(monthString);
string sMonth = DateTime.Now.ToString("MM");
Given that the SQL Month function returns an integer (Source) you need to replace:
"... WHERE Month(P.fromDate)= Month(#Month) GROUP BY ..."
by
"... WHERE Month(P.fromDate) = " + intMonth.ToString() + " GROUP BY ..."
where intMonth is the integer value of the month selected from your combobox.
However, you will need to make sure that it is just an integer and can't be used as an injection attack. You would be better off putting all your SQL into a stored procedure and passing the month as an integer parameter.

how to reference columns in sql server connection in C#

I'm trying to translate some perl code into C# and I'm having some trouble with the following.
After establishing a sql server connection and executing the select statement, how do I reference the different elements in the table columns. For example, in Perl it looks like:
my $dbh = DBI -> connect( NAME, USR, PWD )
or die "Failed to connect to database: " . DBI->message;
my $dbname = DB_NAME;
my $dbschema = DB_SCHEMA;
my $sql = qq{select a,b,c,d,e,f,g,h,i,...
from $dbname.$dbschema.package p
join $dbname.$dbschema.package_download pd on p.package_id = pd.package_id
join $dbname.$dbschema.download d on pd.download_id = d.download_id
where p.package_name = '$package'
--and ds.server_address like 'tcp/ip'
order by a,b,c,d,..};
my $sth = $dbh -> prepare( $sql )
or die "Failed to prepare statement: " . $dbh->message;
$sth -> execute()
or die "Failed to execute statement: " . $sth->message;
#now to go through each row in result table
while ( #data = $sth->fetchrow_array() )
{
print "$data[0]";
# If source server FTP is not already open, make new FTP
if ( $data[0] != $src_id )
{
if ( $src_ftp )
{ $src_ftp -> quit; }
$src_ftp = make_ftp( $data[1], $data[2], $data[3], $data[18], $data[19], $data[20] );
$src_id = $data[0];
}
}
so far I've got it down to
string db = NAME;
string myConnectionString = "Data Source=ServerName;" + "Initial Catalog=" + db + "User id=" + ODBC_USR + "Password=" + PWD
SqlConnection myConnection = new SqlConnection(myConnectionString);
string myInsertQuery = "select a,b,c,d,e,f,g,h,i,...
from $dbname.$dbschema.package p
join $dbname.$dbschema.package_download pd on p.package_id = pd.package_id
join $dbname.$dbschema.download d on pd.download_id = d.download_id
where p.package_name = '$package'
--and ds.server_address like 'tcp/ip'
order by a,b,c,d,..";
SqlCommand myCommand = new SqlCommand(myInsertQuery);
myCommand.Connection = myConnection;
myConnection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
but how do I reference the columns like data[0] and data[1] in C#. Sorry I'm new to both languages so my background is severely lacking. Thanks!
You could reference your column directly by its column name or by numeric order (it starts with 0 as the first column) either through a DataTable, DataSet, DataReader or a specific DataRow.
For the sake of example i'll use a DataTable here and I will name it as dt and let's say we want to reference the first row then you could reference it with the following Syntax/Format:
dt[RowNumber]["ColumnName or Column Number"].ToString();
For example:
dt[0]["a"].ToString();
Or by number the first column with be 0 like:
dt[0][0].ToString();
And use Parameters by the way because without which it would be susceptible to SQL Injection. Here's a more complete code below:
string db = NAME;
string myConnectionString = "Data Source=ServerName;" + "Initial Catalog=" + db + "User id=" + ODBC_USR + "Password=" + PWD
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
string mySelectQuery = #"SELECT a,b,c,d,e,f,g,h,i,...
FROM package p
JOIN package_download pd on p.package_id = pd.package_id
join download d on pd.download_id = d.download_id
WHERE p.package_name = #PackageName
AND ds.server_address LIKE 'tcp/ip%'
ORDER by a,b,c,d";
try
{
connection.Open();
using (SqlDataAdapter da = new SqlDataAdapter(mySelectQuery, connection))
{
using (SqlCommand cmd = new SqlCommand())
{
da.SelectCommand.Parameters.AddWithValue("#PackageName", txtPackage.Text);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count>0) // Make sure there is something in your DataTable
{
String aVal = dt[0]["a"].ToString();
String bVal = dt[0]["b"].ToString();
// You'll be the one to fill up
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I change your LIKE 'tcp/ip' to LIKE 'tcp/ip%' by the way which is the more appropriate one of using LIKE.
you can use ado.net entity data table to reference the tables in your sql server. I don't know if you're asking exactly this but it may help. because direct referencing to sql server is not possible as far as i know.

Categories

Resources