Syntax error displaying database fields in a gridview - c#

I am doing a standard exercise where displaying fields of three tables in a gridview but however have a syntax error in my inner join statement.
Any advice perhaps on where the syntax error lies.
try
{
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source =" + Server.MapPath("App_Data\\Shopping List.mdb"));
conn.Open();
DataSet ds = new DataSet();
OleDbDataAdapter dba = new OleDbDataAdapter(#"SELECT Ingredient.IngerdientId, Ingredient.IngredientName, Area.AreaName, Recipe.RecipeName, Ingredient.Quantity
FROM Ingredient
INNER JOIN Area ON Ingredient.AreaId = Area.AreaId
INNER JOIN Recipe ON Ingredient.RecipeId = Recipe.RecipeId", conn);
dba.Fill(ds);
gridIngredients.DataSource = ds;
gridIngredients.DataBind();
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}

The Access db engine requires parentheses when your FROM clause includes more than one join. I think this may do it, but you would be better off to build and test your SELECT statement within Access using its query designer if you can.
FROM (Ingredient
INNER JOIN Area ON Ingredient.AreaId = Area.AreaId)
INNER JOIN Recipe ON Ingredient.RecipeId = Recipe.RecipeId

Related

SQLite Join command issue Unity

i'm using sqlite database in my Unity project and i need to create a new table using Join statement, like this
string
sql = "create table ResultTable2 as select name_journal from Journal INNER JOIN Points.name_point ON Points.id_journal = Journal.id_journal";
command = new SqliteCommand(sql, ActiveConnection);
command.ExecuteNonQuery();
And I have an exception: "cannot find table Points.name_point"
So how can I do this? I learned that for this you can use linq to sql but I'm not sure if it works in Unity.
Ultimately i need to convert this table to XML file..
I tried this:
var w = "select j.name_journal, p.name_point,w.name_workplace, w.percent_workplace from Journal j INNER JOIN Points p ON p.id_journal = j.id_journal INNER JOIN Workplace w ON w.id_point = p.id_point";
var ds = new DataSet();
using (var da = new SqliteDataAdapter(q, sqc))
{
da.Fill(ds);
}
ds.WriteXml(#"d:\data.xml");
but the xml file was empty.
maybe I didn’t make the request correctly..
Or is it impossible to do in Unity and I need to use Xamarin?
You can't join a column, only a table. You have to select the column from the joined table. Given your second query I feel like you already knew this but just made a mistake. I'd also recommend using a StringBuilder object to build your queries.
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.AppendLine("CREATE TABLE ResultTable2 AS");
sqlBuilder.AppendLine(" SELECT Journal.name_journal, Points.name_point");
sqlBuilder.AppendLine(" FROM Journal");
sqlBuilder.AppendLine(" INNER JOIN Points ON Points.id_journal = Journal.id_journal");
command = new SqliteCommand(sqlBuilder.ToString(), ActiveConnection);
command.ExecuteNonQuery();

Getting a count(1) value to a list in C#

I'm trying to get the count of a column in a table using a SQL query to a C# list
my sample code is below
"Select count(1) as Values, SM.Name from SM INNER JOIN Bill on SM.ID = Bill.AL INNER JOIN Details on Bill.ID = Details.ID"
I need to to add the count to a list<> Can some one tell me how to do that?
Since this count value doesn't have a column name I have given it the name "Values"
I have tried to get the value as following code
public IHttpActionResult Post(Brands brand)
{
DataTable dt = new DataTable();
List<Brands> list = new List<Brands>();
try
{
SqlConnection con =
new SqlConnection(
"MyConnectionString");
con.Open();
var query = "Select count(1) as Values, SM.Name from SM INNER JOIN Bill on SM.ID = Bill.AL INNER JOIN Details on Bill.ID = Details.ID";
SqlCommand com = new SqlCommand(query, con);
com.ExecuteNonQuery();
con.Close();
SqlDataAdapter adptr = new SqlDataAdapter(com);
adptr.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
Brands GetAll = new Brands();
GetAll.Count = Convert.ToInt32(dt.Rows[i]["Values"]);
GetAll.Name = dt.Rows[i]["Name"].ToString();
list.Add(GetAll);
}
}
catch (Exception e)
{
}
return Ok(list);
}
}
}
Thanks Every one for contributing to help me out. Special Thanks to #Kason. What I did was add Group by to SQL Query. That Solved the Issue. Hope this would be helpful to others.
I appriciate the efforsts and suggestion for all helpers,but some
comments are showing they have less knowledge of sql.
1)
you used column(1), please never ever use this syntax for
query,this is bad practice to get data,always use name of column.
2)
Someone posted that count(1) is equals to count() than it's
myth,because count() will provide count of all the rows where
count(1) will provide only count of that which are not null. (Not
believing try this in your system.)
keep this points in mind also
suggest to others,hope you like this post.

Pulling Data from MS Access DataBase to DataGridView using Variable

I am designing a C# Application that pulls Asset Information from an existing MS Access Database.
string conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=O:\IT\IT Hardware\HWInv.accdb";
string dbcmd = "SELECT tblInvCategory.Category, tblInvManufacturer.Manufacturer, tblInvModel.Model, tblInvMaster.SerialNumber, tblInvMaster.InvNumber, tblInvMaster.InvNumberExternal, tblInvCompany.CompanyName, tblInvCustomer.CustomerName, tblInvLocation.Location, tblInvMaster.OfficeNumber, tblInvTechs.TechName, tblInvMaster.TechDate, tblInvMaster.UpdatedBy, tblInvMaster.UpdatedDate, tblInvMaster.DeployDate, tblInvMaster.RetirePlanned, tblInvMaster.Status, tblInvMaster.PONumber, tblInvMaster.Notes, tblInvMaster.Audited FROM tblInvTechs INNER JOIN (tblInvModel INNER JOIN (tblInvManufacturer INNER JOIN (tblInvLocation INNER JOIN (tblInvCustomer INNER JOIN (tblInvCompany INNER JOIN (tblInvCategory INNER JOIN tblInvMaster ON tblInvCategory.CategoryID = tblInvMaster.CategoryID) ON tblInvCompany.CompanyID = tblInvMaster.CompanyID) ON tblInvCustomer.CustomerID = tblInvMaster.CustomerID) ON tblInvLocation.LocationID = tblInvMaster.LocationID) ON tblInvManufacturer.ManufacturerID = tblInvMaster.ManufacturerID) ON tblInvModel.ModelID = tblInvMaster.ModelID) ON tblInvTechs.TechID = tblInvMaster.TechID WHERE (((tblInvCustomer.CustomerName)="+ CustomerName + "))";
OleDbConnection con = new OleDbConnection(conn);
OleDbCommand cmd = new OleDbCommand(dbcmd, con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable CustAssets = new DataTable();
da.Fill(CustAssets);
dataGridView1.DataSource = CustAssets;
I have an existing Query in MS Access for the Local MS Access Form here:
SELECT tblInvCategory.Category, tblInvManufacturer.Manufacturer, tblInvModel.Model, tblInvMaster.SerialNumber, tblInvMaster.InvNumber, tblInvMaster.InvNumberExternal, tblInvCompany.CompanyName, tblInvCustomer.CustomerName, tblInvLocation.Location, tblInvMaster.OfficeNumber, tblInvTechs.TechName, tblInvMaster.TechDate, tblInvMaster.UpdatedBy, tblInvMaster.UpdatedDate, tblInvMaster.DeployDate, tblInvMaster.RetirePlanned, tblInvMaster.Status, tblInvMaster.PONumber, tblInvMaster.Notes, tblInvMaster.Audited
FROM tblInvTechs INNER JOIN (tblInvModel INNER JOIN (tblInvManufacturer INNER JOIN (tblInvLocation INNER JOIN (tblInvCustomer INNER JOIN (tblInvCompany INNER JOIN (tblInvCategory INNER JOIN tblInvMaster ON tblInvCategory.CategoryID = tblInvMaster.CategoryID) ON tblInvCompany.CompanyID = tblInvMaster.CompanyID) ON tblInvCustomer.CustomerID = tblInvMaster.CustomerID) ON tblInvLocation.LocationID = tblInvMaster.LocationID) ON tblInvManufacturer.ManufacturerID = tblInvMaster.ManufacturerID) ON tblInvModel.ModelID = tblInvMaster.ModelID) ON tblInvTechs.TechID = tblInvMaster.TechID
WHERE (((tblInvCustomer.CustomerName)=[Forms]![frmInvSelectCustomerName]![CustomerName]));
The SQL command is failing when inserted as above. The Varible Customer Name is used to pull just those records for that user from the Access Database but it is failing when compiled and run.
The Call stack outputs this is the Text Visualizer:
Syntax error (missing operator) in query expression '(((tblInvCustomer.CustomerName)=Joe Smith))'.
It appears my issue is in the WHERE statment.
Any help is much appreciated.
Thanks,
If you use a parameterized query you avoid this kind of problems.
The error arises because, if the CustomerName field is a string every value used in a condition should be enclosed in single quotes.
However, manually setting the quotes is dangerous for possible Sql Injections and could cause other syntax errors if the string used as value contains itself a single quote.
Using a parameterized query avoid all of this
string dbcmd = "SELECT ...... " & _
"WHERE (((tblInvCustomer.CustomerName)=?))";
And then
using(OleDbConnection con = new OleDbConnection(conn))
using(OleDbCommand cmd = new OleDbCommand(dbcmd, con))
using(OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("#p1", CustomerName);
DataTable CustAssets = new DataTable();
da.Fill(CustAssets);
dataGridView1.DataSource = CustAssets;
}
here's a link leading to a post with a problem a bit similar to yours. you might want to check this out first:
http://social.msdn.microsoft.com/Forums/en-US/8ee73442-f28b-49ab-a4d9-8b550f841aa4/binding-ms-access-db-to-a-datagrid-view-in-c-windows-forms?forum=winformsdatacontrols

Loading DataTable with multiple tables select query

I never used select queries with multiple tables involved before and now when I do, I'm having troubles with getting the information from the DataTable.
I have this query:
SELECT *
FROM [Usergroups], [Groups]
WHERE [Usergroups.UserID] = #name
AND [Groups.GroupID] = [Usergroups.GroupID]
And this is how I get the returned values into a DataTable:
DataTable groupsTable = new DataTable();
groupsTable.Load(sqlCmd.ExecuteReader());
Now, how can I specify my DataTable from which table I want to take rows from? For example, this is what I did before multiple tables where involved:
string groupName = groupsTable.Rows[0]["Name"];
I could not find any resource with such information, but I know it's a basic question. Thanks in advance.
The query in your question doesn't produce, as a result, multiple tables.
It produces a JOIN between two tables.
As a consequence, on the C# side, you don't have two tables but just one as before, with the all fields from both tables.
As a side note, a better way to JOIN tables together is through the use of the JOIN statement like this
SELECT * -- a field list is better here ---
FROM Usergroups ug INNER JOIN Groups g ON g.GroupID=ug.GroupID
WHERE ug.UserID=#name
and you should add, to the SELECT clause, a list of the fields that you are really interested in.
SEE a simple JOIN reference
If you want to retrieve the values of the two tables in separate DataTable objects, then you need to use a DataSet in this way
DataSet ds = new DataSet();
DataTable dtUserGroups = new DataTable("UserGroups");
DataTable dtGroups = new DataTable("Groups");
ds.Tables.Add(dtUserGroups );
ds.Tables.Add(dtGroups);
using(SqlCommand cmd = new SqlCommand("SELECT * FROM UserGroups;SELECT * from Groups", con))
{
using(SqlDataReader dr = cmd.ExecuteReader())
{
ds.Load(dr, LoadOption.OverwriteChanges, dtUserGroups, dtGroups);
// Now you have the two tables filled and
// you can read from them in the usual way
}
}
This last example could further enhanced adding a DataRelation object to the DataSet to represent the relationship between the two tables. This could allow your code to navigate the parent/child recordset.
You may try in this way :
string query = "SELECT U.ID,U.NAME, C.NAME AS CUSTOMERNAME, C.DOB FROM USER U INNER JOIN CUSTOMER C ON U.ID = C.USERID"
SqlConnection conn = new SqlConnection(_connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
Above code will return you one DataTable with data from two different tables say "User" and "Customer".
I hope now you know how to access data from a DataTable.
It is better to use JOIN for combining multiple tables such as INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL JOIN as per your requirements. So, when you use INNER JOIN, it will have the columns of two joined tables, i.e., if
tblA has a, b,c as columns and
tblB has a, e,f as columns
then the inner joined table will have a, b, c, e, f as its columns.
Then, you can use like this:
public DataTable LoadData()
{
DataTable dataTable;
string connString = #"your connection string here";
string query = "SELECT * FROM Usergroups t1 INNER JOIN Groups t2 ON t2.GroupID=t1.GroupID WHERE t1.UserID=#name";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
conn.Close();
return dataTable;
}
After Getting the DataTable, then you can use this table like:
DataTable dt = LoadDataClass.LoadData();
string groupName = dt.Rows[0]["Name"]; //For first row
I hope you get it.
in wpf c#, this method can also be used to retrieve data from multiple tables
try
{
using (SqlConnection conn = new SqlConnection(_pageDataBase.connectionString()))
{
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter Usergroups= new SqlDataAdapter("select *from Usergroups", conn);
Usergroups.Fill(dt);
SqlDataAdapter Groups= new SqlDataAdapter("select *from Groups", conn);
Groups.Fill(dt);
datagridName.ItemsSource = dt.DefaultView;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

merging two datasets and display in one gridview

I have two seperate databases from which I want to retrieve data and display in one grid view. The difficult I have is that I have a product key only in the table from the one database and the same set of product keys agains the actual products products in the other database and now I want to display the product data in one grid view....if this makes sense.
How can I do this, merge the data and display the product data agains the keys in the one grid.
string connString = "Data Source=.\\SQLEXPRESS;Initial Catalog=LRVWebsite;user ID=sa;password=lrmg;";
SqlConnection sqlCon;
OleDbConnection conn;
DataSet setOleDb;
DataSet dsSql;
private void bindData()
{
try
{
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source =" + Server.MapPath("App_Data\\LR Product Database 2000.mdb"));
conn.Open();
setOleDb = new DataSet();
OleDbDataAdapter dbaOle = new OleDbDataAdapter("SELECT * FROM tblProducts", conn);
dbaOle.Fill(setOleDb);
sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["LRVWebsite"].ToString());
sqlCon.Open();
dsSql = new DataSet();
SqlDataAdapter dba = new SqlDataAdapter(#"SELECT C.CustomerFirstName,C.CustomerLastName, C.CustomerCompany,C.CustomerPosition,C.CustomerCountry,C.CustomerProvince,C.CustomerContact,CP.ActionDate,CP.ProductCode,CP.CustomerEmail FROM tblCustomers C INNER JOIN tblCustomerProducts CP ON C.CustomerEmail = CP.CustomerEmail ORDER BY ActionDate DESC", connString);
//#"SELECT C.CustomerFirstName,C.CustomerLastName,C.CustomerCompany,C.CustomerPosition,C.CustomerCountry,C.CustomerProvince,C.CustomerContact,CP.ActionDate,CP.ProductCode,CP.CustomerEmail FROM tblCustomers C INNER JOIN tblCustomerProducts CP ON C.CustomerEmail = CP.CustomerEmail ORDER BY ActionDate DESC", connString);
dba.Fill(dsSql);
dsSql.Merge(setOleDb);
GridView1.DataSource = dsSql;
GridView1.DataBind();
sqlCon.Close();
This is what I have tried.Now, how can I get the product key to correlate with the actual product in the other table which contains the same product key?
I think this is a commonly faced scenario. Here is a detailed link from msdn.
Merge Data Set Contents
As much as I understand, you have 2 tables in one database and one table in the other database and you are wanting to combine all of these data set and display it as one.
If I am correct then you can do joins across the databases;
select * from dbo.firstdatabasetable db1
inner join apple.primarykeys db2
on db2.primary = db1.primary
inner join orange.seconddatabase db3
on db2.productname = db3.productname
If databases are hosted on different Machines across the network then you can find the DB servers with select sys.servers
Lets say the the first server is x and the second one is y
then;
select * from x.dbo.firstdatabasetable db1
inner join x.dbo.primarykeys db2
on db2.primary = db1.primary
inner join y.dbo.seconddatabase db3
on db2.productname = db3.productname
inner join x.dbo.primarykeys

Categories