SQLite Join command issue Unity - c#

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();

Related

C# Azure Function DataTable missing values in one column but looks ok in SSMS

I have an blob triggered Azure Function doing some ETL from an uploaded file into some tables in SQL db and then creating output files afterward from sql views/statements/storedprocs.
I am retrieving data from a SQL view and filling it into a DataTable in an Azure Function. I have several of these in the function and only one instance has missing values.
Code in Azure Function
SqlConnection con = new SqlConnection("connection string");
SqlCommand comm = new SqlCommand("SELECT * FROM table_view", con);
SqlDataAdapter da = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
table_view
SELECT TOP 99.9999 PERCENT 'DD' as 'ColumnType'
,EIT.IndexID as 'index_id' -- 'Benchmark_Code'
,CONVERT(varchar(8),EIT.AsOfDate,112) AS 'as_of_date' -- 'AsOfDate'
,BP.OneMonth as 'cum_1m_ror'
,BP.ThreeMonth as 'cum_3m_ror'
,BP.YTD as 'cum_ytd_ror'
,BP.Ann1Year as 'cum_1y_ror'
,BP.Ann3Year as 'ann_3y_ror'
,BP.Ann5Year as 'ann_5y_ror'
,BP.Ann10Year as 'ann_10y_ror'
,CT.strippedcontent as 'benchmark_description'
-- ,EIT.BenchmarkDesc AS 'benchmark_description' -- this works
-- ,CONVERT(nvarchar(MAX),CT.strippedcontent) as 'benchmark_description' -- tried this too
FROM (
SELECT DISTINCT *
FROM dbo.tableA
) EIT
INNER JOIN dbo.tableB BM
ON BM.ClientBenchCode = EIT.IndexID
AND BM.ClientID = 61
INNER JOIN dbo.tableC BP
ON BP.BenchmarkID = BM.BenchMarkID
AND BP.AsofDate = EIT.AsOfDate
-- for benchmark desc
INNER JOIN dbo.tableD CM
ON CM.LinkedEntityID = BM.BenchMarkID
INNER JOIN dbo.tableE CT
ON CT.ContentMapID = CM.ContentMapID
WHERE CT.ContentCategoryID = 459
and CT.PublishedFlag = 1
ORDER BY index_id, as_of_date
da.Fill(dt) does not fill in the values for benchmark_description
but when using SSMS, the sql view returns the correct data.
If I replace the values of the benchmark_description in the view, using EIT.BenchmarkDesc instead of CT.strippedcontent it works.
results from SSMS:
results from DataTable in Az Func:
EIT.BenchmarkDesc type is varchar(4000)
CT.strippedcontent type is text
I tried converting/casting the values of the column in question within the sql view.

Populating Datagrid with Data from Multiple Tables

I need to populate a datagrid with the following columns.
invnumber,itemname,rate,quantity..
itemname,rate,quantity comes from 1 table while invnumber comes from another table
I used to do like this
string commandText = "SELECT invnumber,cname,date FROM inv_table WHERE invnumber LIKE #id";
SqlCommand command = new SqlCommand(commandText, conn);
string searchParam = String.Format("%{0}%", text_inv.Text);
command.Parameters.AddWithValue("#id", searchParam);
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView2.DataSource = dt;
}
}
Now i cannot directly assign the data source as 2 different tables are involved
dataGridView2.DataSource = dt;
How can i get around this.
To emit combined result from 2 or more different tables in a table, use either INNER JOIN, LEFT JOIN, RIGHT JOIN or UNION statement depending on your need.
In this case, you need to join first table and other table to get desired results, assume invnumber is unique or primary key. Here is an example:
string commandText = "SELECT other.invnumber, inv.cname, inv.date FROM inv_table AS inv
INNER JOIN other_table AS other
ON inv.invnumber = other.invnumber
WHERE other.invnumber LIKE #id";
Or if you have already defined classes for each table, use LINQ to SQL with lambda expression:
DataContext dc = new DataContext();
var results = dc.InvTable.Join(OtherTable, inv => inv.invnumber, other => other.invnumber, (inv, other) => new { invnumber = other.invnumber, cname = inv.cname, date = inv.date });
Any improvements and suggestions welcome.
Create a new class for the data structure of the 2 different table, populate the new one and use. (easier and the most clear solution)

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

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

Syntax error displaying database fields in a gridview

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

Categories