So, I'm using C# winrt with SQLite database. I want to display the results of the query which i have "join"ed.
I have 2 tables which are Student and Course.
Student has : id(PK), name, courseid
Course has : courseid(PK), coursename
And here is my code :
var query1 = conn.QueryAsync<Student>("select * from Student s inner Join Course c on s.courseid = c.courseid");
var query2 = conn.QueryAsync<Course>("select * from Course c inner join Student s on c.courseid = s.courseid");
var result1 = await query1;
var result2 = await query2;
lstJoin.Items.Clear();
foreach (var item in result1)
{
string text = "Name: " + item.name + ", Course Id: " + item.courseid + ", Course Name : " + item.coursename;
lstJoin.Items.Add(text);
}
But the "item.coursename" is error, so i can't display it. And then, if I change result1 in foreach with result 2, "item.name" will be error. What should I do so I can display both of them? Thank you.
Why don't you do it in classic way? like SQLiteCommand object with command text:
strCommandText = "SELECT tbl1.*,tbl2.* FROM Table1 tbl1 INNER JOIN Table2 tbl2 ON tbl1.ID = tbl2.ID";
Or is it a specification that you need to use it this way??
Because I had the same issue when I was using the SQLite Helper file.
Related
I am creating a form that I can add a menu item to display All Suppliers and Suppliers Quantity by Part number. So I got ReportSupplierDisplayALl to work when I ran. But When I try to run the form for the ReportSuppliersDisplayByPartnumber because When I enter the SupplierID and when I did it threw an exception.
When it throws an exception, what does it mean by incorrect syntax?
public DataTable DisplaySupplierByPartNumber(string PartNumber)
{
// Add using System.Data
string queryString = "SELECT Suppliers.SupplierName, Suppliers.Email, Parts.PartName, SUM(Inventory.Quantity) AS SumOfQuantity, PartNumber " +
"FROM ((Suppliers INNER JOIN Parts ON Suppliers.SupplierID = Parts.Supplier) INNER JOIN Inventory ON Parts.PartNumber = Inventory.PartNumber " +
"INNER JOIN Employees ON Inventory.EmpID = Employees.EmpID " +
"GROUP BY Suppliers.SupplierName, Suppliers.Email, Parts.PartName, Parts.PartNumber " +
"HAVING Parts.PartNumber = #PartNumber " +
"ORDER BY Suppliers.SupplierName ";
using (SqlConnection con = new SqlConnection(_strCon))
{
try
{
SqlCommand command = new SqlCommand(queryString, con);
command.Parameters.AddWithValue("#PartNumber", PartNumber );
con.Open();
SqlDataReader reader = command.ExecuteReader();
DataTable theTable = new DataTable();
theTable.Load(reader);
return theTable;
}
catch (Exception ex)
{
throw ex;
}
}
enter image description here
enter image description here
Don't use "" For String use # "Your Query And Make Sure You get all bracket correct"
also change element take part number first then use your aggerate function
string queryString = #"SELECT S.SupplierName, S.Email, P.PartName, SUM(Inventory. Quantity) AS SumOfQuantity FROM Suppliers as s
INNER JOIN Parts as p on P.SupplierId=P.SupplierId
INNER JOIN Inventory ON Parts.PartNumber = Inventory.PartNumber
INNER JOIN Employees ON Inventory.EmpID = Employees.EmpID
GROUP BY S.SupplierName, S.Email, P.PartName, P.PartNumber
HAVING Parts.PartNumber = #PartNumber
ORDER BY S.SupplierName"
I'm executing the following code:
public ActionResult BranchUser(int ? idBranch)
{
CtrForm objCtrForm = new CtrForm();
objCtrForm.Connect();
objCtrForm.query.Connection = objCtrForm.connection;
objCtrForm.query.CommandType = CommandType.Text;
List<tblUser> listBranchUser = new List<tblUser>();
string sql = #"SELECT B.name, B.phone, B.email, B.idUser FROM tblBranchUser A
INNER JOIN tblUsers B ON A.idUser = B.idUser
WHERE A.idBranch = " + idBranch;
objCtrForm.query.CommandText = sql;
objCtrForm.connection.Open();
SqlDataReader sReader = objCtrForm.query.ExecuteReader();
while (sReader.Read())
{
listBranchUser.Add(
new tblUser
{
idUser = Convert.ToInt32(sReader["idUser"]),
name = Convert.ToString(sReader["name"]),
phone = Convert.ToString(sReader["phone"]),
email = Convert.ToString(sReader["email"])
}
);
}
objCtrForm.connection.Close();
return View(listBranchUser);
}
but I got the following error when I call the function:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
I don't understand why I get this, due to I executed in other functions but I only called one table, not two. Any advice I will appreciate.
I believe C# won't implicitly convert an integer to a string.
Try replacing
string sql = #"SELECT B.name, B.phone, B.email, B.idUser FROM tblBranchUser A
INNER JOIN tblUsers B ON A.idUser = B.idUser
WHERE A.idBranch = " + idBranch;
With
string sql = #"SELECT B.name, B.phone, B.email, B.idUser FROM tblBranchUser A
INNER JOIN tblUsers B ON A.idUser = B.idUser
WHERE A.idBranch = " + idBranch.ToString();
I have a C# application that displays products that a company sells. Next to that column is the product type and in the last column is the number of customers that have bought that product. This is my SQL query to populate the first two columns:
string selectQuery;
selectQuery = "SELECT Products.ProductID, Products.ProductTypeID, ";
selectQuery = selectQuery + "Products.ProductName, Products.YearlyPremium, ProductTypes.ProductType ";
selectQuery = selectQuery + "FROM Products ";
selectQuery = selectQuery + "INNER JOIN ProductTypes ON Products.ProductTypeID = ProductTypes.ProductTypeID "
Now I need to work out how many customers bought each product. I guess I need to use the COUNT(*) method to get CustomerID's but now sure how to integrate it into this query.
Here is the schema
The code I use to display the data in the listView is this:
SqlConnection conn = ConnectionsManager.DatabaseConnection();
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(selectQuery, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Products product = new Products(int.Parse(rdr["ProductID"].ToString()),
int.Parse(rdr["ProductTypeID"].ToString()),
rdr["ProductName"].ToString(),
Math.Round(decimal.Parse(rdr["YearlyPremium"].ToString()), 2));
ProductTypes productType = new ProductTypes(int.Parse(rdr["ProductTypeID"].ToString()),
rdr["ProductType"].ToString());
ListViewItem lvi = new ListViewItem(product.ProductName.ToString());
lvi.SubItems.Add(productType.ProductType.ToString());
\\lvi.SubItems.Add(customer.CustomerID.ToString()); <---this will be the line to display the customer count
lvMain.Items.Add(lvi);
}
if (rdr != null)
rdr.Close();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Unsuccessful" + ex);
}
Considering that ProductTypeId is has to be a NON NULL value in final result (hence using INNER JOIN), the SQL part which you will have to embed in your C# code:
SELECT P.ProductID, P.ProductTypeID, P.ProductName, P.YearlyPremium, PT.ProductType, CustomerCount = COUNT(S.CustomerID)
FROM Sales S
INNER JOIN Products P
ON S.ProductID = P.ProductID
INNER JOIN ProductTypes PT
ON P.ProductTypeID = PT.ProductTypeID
GROUP BY P.ProductID, P.ProductTypeID, P.ProductName, P.YearlyPremium, PT.ProductType
Note:- Since you do not need any attribute of the customer, and you have a foreign key on Sales.CustomerID column to Customer.CustomerId column, hence for the purpose of getting the CustomerCount, join to Customer table is not necessary.
You would seem to want a basic GROUP BY query:
SELECT p.ProductID, p.ProductTypeID, p.ProductName, p.YearlyPremium,
pt.ProductType,
COUNT(DISTINCT s.CustomerID) as num_customers
FROM Products p INNER JOIN
ProductTypes pt
ON p.ProductTypeID = PT.ProductTypeID LEFT JOIN
Sales S
ON s.ProductID = p.ProductID
GROUP BY p.ProductID, p.ProductTypeID, p.ProductName, p.YearlyPremium, pt.ProductType;
Notes:
This uses a LEFT JOIN to Sales to get products that have no sales.
This uses an INNER JOIN to ProductTypes because, presumably, all products have a type.
The GROUP BY has all non-aggregated columns.
This counts unique customer ids, because the same customer may have purchased the same product on more than one occasion. If you just want a count of the records in Sales, remove the DISTINCT.
try using Group by clause. It will work.
Example:
SELECT COUNT(ProductId),CustomerId
FROM Product
GROUP BY CustomerId;
kind of this
I want to get the data from my access database and show the data at Datagridview. my tables are:
TABLE 1(AB) TABLE 2(CD) TABLE 3(EF) TABLE 4(GH)
------------- ----------------- ------------- -------------------
SID SName CID TID TID TName Tprice FID CID FCp FPID FID FCp Fprice
The query which I am using to retrieve the data in C# is:
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
command1.CommandText = "select T.TName, T.Tprice, P.FCp, P.Fprice from (([AB] S inner join [CD] T on S.TID = T.TID) (inner join [EF] C on S.CID = C.CID) inner join [GH] P on C.FID = P.FID where (S.SID = 2) ";
OleDbDataReader myreader = command1.ExecuteReader();
while (myreader.Read())
{
//DATA IS READ HERE
}
The error which I am getting is:
Syntax error at JOIN expression
I want TName, Tprice, FCp(TABLE 4), Fprice as my output. Am I doing it right or is there any other way to do that.
In your from you have opening parentheses with no closing (the first one).
Besides fixing the parentheses it is much more readable if you jump lines:
command1.CommandText = #"select T.TName, T.Tprice, P.FCp, P.Fprice
from (([AB] S
inner join [CD] T on S.TID = T.TID)
inner join [EF] C on S.CID = C.CID)
inner join [GH] P on C.FID = P.FID
where S.SID = 2";
(Access requires parentheseses)
Table i need to sort
So i got this 5 drop downs i need to use for sorting output from sql
Now i use
DropDownList_Instruktorer.Items.Insert(0, new ListItem("Vælg Instruktør", "*"));
For the Default Value, and i was thinking this will do the job. But
cmd.Parameters.addwithvalue
enter the value into value obviously instead of use * to show all results like it normally does in sql
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Hold
INNER JOIN Instruktorer
ON instruktor_id = fk_in_id
INNER JOIN Stilarter
ON stilart_id = fk_st_id
INNER JOIN Aldersgruppe
ON aldersgruppe_id = fk_ag_id
INNER JOIN Niveauer
ON niveau_id = fk_ni_id
INNER JOIN Tider
ON tid_id = fk_ht_id
WHERE fk_in_id = #Instruktor AND
fk_st_id = #Stilart AND
fk_ag_id = #Aldersgruppe AND
fk_ni_id = #Niveau AND
fk_ht_id = #Tid", conn);
cmd.Parameters.AddWithValue("#Instruktor", DropDownList_Instruktorer.SelectedValue);
cmd.Parameters.AddWithValue("#Stilart", DropDownList_Stilart.SelectedValue);
cmd.Parameters.AddWithValue("#Aldersgruppe", DropDownList_Aldersgrupper.SelectedValue);
cmd.Parameters.AddWithValue("#Niveau", DropDownList_Niveauer.SelectedValue);
cmd.Parameters.AddWithValue("#Tid", DropDownList_Tider.SelectedValue);
Here is my sql, Any idea how i can i get it to work without writing 25 if statements?
Why not use a string in place of the AddWithValue, eg:
string instructorStr = "";
string stilartStr = "";
...
if (DropDownList_Instruktorer.SelectedValue != "*")
{
instructorStr = "fk_in_id = " + DropDownList_Instruktorer.SelectedValue + " AND";
}
if (DropDownList_Stilart.SelectedValue != "*")
{
stilartStr = "fk_st_id = " + DropDownList_Stilart.SelectedValue + " AND";
}
...
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Hold
INNER JOIN Instruktorer
ON instruktor_id = fk_in_id
INNER JOIN Stilarter
ON stilart_id = fk_st_id
INNER JOIN Aldersgruppe
ON aldersgruppe_id = fk_ag_id
INNER JOIN Niveauer
ON niveau_id = fk_ni_id
INNER JOIN Tider
ON tid_id = fk_ht_id
WHERE " +
instructorStr +
stilartStr +
...
+ " 1 = 1", conn);
Then you have the option to do all sorts of stuff with the individual variables, including ORDER BY
Using Stringbuilder would be cleaner but it's easier to show it this way.