how to insert from different inputs - c#

i am trying to insert different values into a table from my database , i retrieve these values from different tables , input from textBox in Windows form etc ..
but the syntax of my query is not correct , i want to know if there is a possiblity to insert these inputs in one query :
String query4 = #"INSERT INTO FACFIN
(Nom_pren_RS,trimestre,exercice,Nb_factures,Prix_total_HT)
values
('" + textBox1.Text + "','" + textBox3.Text + "','" + textBox2.Text + "',
SELECT cast(count(trimestre) AS varchar(6)) AS Nb_factures FROM facture
WHERE
(facture.Nom_pren_RS='" + textBox1.Text + "'),
SELECT cast(SUM (cast(Prix_vente_HT AS BIGINT ))AS varchar(15))
from facture
where (facture.Nom_pren_RS='" + textBox1.Text + "') ) ";
i know that there is a risk of sql injection and i know that i have to use parameters but i just wanted to test the code to see if it does insert , the syntax of the insert is probably wrong
the nb_factures it should be varchar(6) so i casted it
the column Prix_vente_HT in table facture is varchar so i casted it
to BIGINT to execute the SUM and then casted the SUM to varchar
because the Prix_total_HT should be varchar in the table FACFIN

You cannot add a select statement to a values list, instead this select statement keeps your aggrigates but brings the text box values into a single select statement. If you need to pull rows from multiple tables you can also do a UNION on the select section.
String query4 = #"INSERT INTO FACFIN (Nom_pren_RS,trimestre,exercice,Nb_factures,Prix_total_HT)
SELECT '" + textBox1.Text + "','" + textBox3.Text + "','" + textBox2.Text + "', cast(count(trimestre) AS varchar(6)) AS Nb_factures ,
cast(SUM (cast(Prix_vente_HT AS BIGINT ))AS varchar(15)) as Prix_total_HT
FROM facture
WHERE (facture.Nom_pren_RS='" + textBox1.Text + "')";
The result would look something like this to SQL Server
INSERT INTO FACFIN (Nom_pren_RS,trimestre,exercice,Nb_factures,Prix_total_HT)
SELECT
'TEXT_BOX_1_VALUE','TEXT_BOX_3_VALUE','TEXT_BOX_2_VALUE',
cast(count(trimestre) AS varchar(6)) AS Nb_factures, cast(SUM (cast(Prix_vente_HT AS BIGINT ))AS varchar(15)) as Prix_total_HT
FROM facture WHERE (facture.Nom_pren_RS='TEXT_BOX_1_VALUE')

Related

C# MYSL Insert query cannot update or add a child row

This is the error i get Cannot add or update a child row:
a foreign key constraint fails (selo.klijent, CONSTRAINT
klijent_ibfk_1 FOREIGN KEY (GradID) REFERENCES grad (GradID))
this is my insert query
string insertQuery = " INSERT INTO selo.Klijent(KlijentID,Ime,Prezime,Adresa,GradID,Telefon,Email,AktivanKlijent) Values('" + TB_Sifra + "','" + TB_Ime.Text + "','" + TB_Prezime.Text + "','" + TB_Adresa.Text + "','" + CB_Gradovi + "','" + TB_Telefon + "','" + TB_Mail.Text + "','" + proveraRB() + "')";
and this is my mysql code
create table Klijent(
KlijentID INT NOT NULL AUTO_INCREMENT primary key,
Ime varchar(20) not null,
Prezime varchar(20) not null,
Adresa varchar(20) not null,
GradID INT NOT NULL,
Telefon int not null,
Email varchar(20),
AktivanKlijent varchar(2),
FOREIGN KEY (GradID) REFERENCES Grad(GradID)
);
Really not sure what to do here
check Grad table - GradID column have the GradID value
PS.you have to know :
How does the SQL injection from the “Bobby Tables” XKCD comic work?
You didn't provide an existing GradID.
Furthermore you shouldn't pass a KlijentID because that is an autoincrement. Besides, your code can be hacked: better use a parametrized query.
I didnt convert CB value to int.

Ambiguous column name in c# but not in SQL Server?

I am trying to execute a SQL command via c# but is telling me that I have an ambiguous column name. When I copy the query into SQL Server and execute it, it works fine. But through c#, it tells me
Ambiguous column name 'SPCode'
This is my SQL string in c#:
string yourSQLstring =
"INSERT INTO totalTable (Catalogue, totalTable.SPCode, ProjNo, Quantity, Spare) " +
"SELECT Catalogue, BOMtable.SPCode, ProjNo, SUM(Quantity) AS Quantity, (SELECT CEILING(CAST (.1 * SUM(Quantity) AS FLOAT))) AS Spare FROM MainSuperTable4 " +
"FULL OUTER JOIN BOMtable ON PartNo = Catalogue " +
"WHERE ProjNo= '" + SavingData.instance.projNumber + "' AND SPCode IS NOT NULL " +
"GROUP BY Catalogue, ProjNo, SPCode";
This the code copied into SQL Server and edited to remove c# stuff:
INSERT INTO totalTable (Catalogue, SPCode, ProjNo, Quantity, Spare)
SELECT
Catalogue, SPCode, ProjNo,
SUM(Quantity) AS Quantity,
(SELECT CEILING(CAST (.1 * SUM(Quantity) AS FLOAT))) AS Spare
FROM MainSuperTable4
FULL OUTER JOIN BOMtable ON PartNo = Catalogue
WHERE
ProjNo = 'P140134' AND SPCode IS NOT NULL
GROUP BY
Catalogue, ProjNo, SPCode
Not sure why it would work in SQL Server and then not in C#?
Thanks for any help!
Change your group by to this:
"GROUP BY Catalogue, ProjNo, BOMtable.SPCode";
Change your insert to this:
"INSERT INTO totalTable (Catalogue, SPCode, ProjNo, Quantity, Spare) " +

Make it appear in Not-Submitted list

I want to retrieve back Student names and Student ID that don't exist in the Submission table, but exist in the Students table, and bind it into the GridView. For example Class A has 40 students, but only 38 students submitted the project. I want the 2 students who don't submit to appear in the GridView where the Teacher can view it
SELECT *
FROM Students
LEFT JOIN dbo.Submission ON Students.Student_Id = Submission.Student_Id
AND Students.Subject_Id = Submission.Subject_Id
WHERE Students.Subject_Class='" + Session["Subject_Class"].ToString() + "'
AND Students.Subject_Id = '" + Session["Subject_Id"].ToString() + "'
AND Submission.Proj_Sub = '" + Session["Proj_Sub"].ToString() + "'
And Submission.Student_Id IS NULL
When I use the above-mentioned statement, the GridView appears to be empty.
You probably want something like this.
SELECT *
FROM Students
WHERE Students.Subject_Class='" + Session["Subject_Class"].ToString() + "'
AND Students.Subject_Id = '" + Session["Subject_Id"].ToString() + "'
AND NOT EXISTS (SELECT *
FROM Submissions
WHERE Submissions.Student_Id = Students.Student_Id
AND Submissions.Subject_Id = Students.Subject_Id
AND Submissions.Proj_Sub = '" + Session["Proj_Sub"].ToString() + "')
There are a number of approaches you could take, but this seems like the cleanest. Most importantly, though, you should place emphasis on moving away from your currently-SQL-injection prone approach. Please parameterize your queries.

SQL Query to C#

I am writing this query that I want to transition into C# but I get an error.
The error:
Incorrect syntax near the keyword 'SELECT'.
Incorrect syntax near 'Products'.
Here is the query I am trying to run.
Select
[ID]
,[ProductTypeID]
,[SeriesID]
,[PartNumber]
,[Title]
,[SEOFriendlyURLTitle]
,[HTMLDescription]
,[HTMLValueAdded]
,[RoHSCompliant]
,[ULCompliant]
,[CECompliant]
,[Series]
,[BUSINESS_UNIT]
,[PACKAGING_TYPE]
,[PACK_QTY]
,[MOQ]
,[ORDER_MULTIPLE]
,[LEAD_TIME_WEEKS]
,[INTERNATIONAL_HARMONIZE_CODE]
,[ECCN_NUMBER]
,[COUNTRY_OF_ORIGIN]
,[IS_PART_STATIC_SENSITIVE]
,[IS_PART_LEAD_PB_FREE]
,[MOISTURE_SENSITIVITY_LEVEL_MSL]
,[REGISTERABLE]
,[TAPE_WIDTH]
,[TAPE_MATERIAL]
,[QtyOnHand]
,[QtyOnSalesOrder]
,[QtyOnBackOrder]
,[ProductLine]
,[Reach138Compliant]
,[ConflictMinerals]
,[WebEnabled]
,[DateAdded]
,[UpdateDate]
,[Reviewed]
,[ReviewedBy]
,[Deleted]
,[Book]
,[CustomSort]
,[ONEK]
,[FIVEK]
,[TENK]
,[TWENTYFIVEK]
,[Fifty]
,[OneHundred]
,[FiveHundred]
FROM Products.Products
Join
(SELECT Products.Prices.ProductID,
Max(IIf(Products.Prices.Code='ONEK',Products.Prices.Price,Null)) AS ONEK,
Max(IIf(Products.Prices.Code='FIVEK',Products.Prices.Price,Null)) AS FIVEK,
Max(IIf(Products.Prices.Code='TENK',Products.Prices.Price,Null)) AS TENK,
Max(IIf(Products.Prices.Code='TWENTYFIVEK',Products.Prices.Price,Null)) AS TWENTYFIVEK,
Max(IIf(Products.Prices.Code='Fifty',Products.Prices.Price,Null)) AS Fifty,
Max(IIf(Products.Prices.Code='OneHundred',Products.Prices.Price,Null)) AS OneHundred,
Max(IIf(Products.Prices.Code='FiveHundred',Products.Prices.Price,Null)) AS FiveHundred
FROM Products.Prices
GROUP BY Products.Prices.ProductID
) As pp
ON Products.Products.ID = pp.ProductID
Here is the query in C#:
y1.CommandText = "Select [ID], [PartNumber], [Book], [HTMLDescription], [HTMLValueAdded], [RoHSCompliant], [ULCompliant],[CECompliant], [Series], [BUSINESS_UNIT], [ONEK], [FIVEK], [TENK], [TWENTYFIVEK]" +
",[Fifty], [OneHundred], [FiveHundred], [PACKAGING_TYPE], [PACK_QTY], [MOQ], [ORDER_MULTIPLE], [LEAD_TIME_WEEKS], [INTERNATIONAL_HARMONIZE_CODE], [ECCN_NUMBER], [COUNTRY_OF_ORIGIN]" +
",[IS_PART_STATIC_SENSITIVE], [IS_PART_LEAD_PB_FREE], [MOISTURE_SENSITIVITY_LEVEL_MSL], [REGISTERABLE], [TAPE_WIDTH], [TAPE_MATERIAL], [Reach138Compliant], [ConflictMinerals], [WebEnabled]" +
"FROM Products.Products" +
"Join" +
"(SELECT Products.Prices.ProductID," +
"Max(IIf(Products.Prices.Code='ONEK',Products.Prices.Price,Null)) AS ONEK," +
"Max(IIf(Products.Prices.Code='FIVEK',Products.Prices.Price,Null)) AS FIVEK," +
"Max(IIf(Products.Prices.Code='TENK',Products.Prices.Price,Null)) AS TENK," +
"Max(IIf(Products.Prices.Code='TWENTYFIVEK',Products.Prices.Price,Null)) AS TWENTYFIVEK," +
"Max(IIf(Products.Prices.Code='Fifty',Products.Prices.Price,Null)) AS Fifty," +
"Max(IIf(Products.Prices.Code='OneHundred',Products.Prices.Price,Null)) AS OneHundred," +
"Max(IIf(Products.Prices.Code='FiveHundred',Products.Prices.Price,Null)) AS FiveHundred" +
"FROM Products.Prices" +
"GROUP BY Products.Prices.ProductID" +
") As pp" +
"ON Products.Products.ID = pp.ProductID" +
"where partnumber like '6%'";
Please help and thank you.
Take this segment as an example:
"FROM Products.Products" +
"Join" +
When these strings are concatenated, you get:
"FROM Products.ProductsJoin"
You need to include the spaces.
"FROM Products.Products " +
"Join" +
You are missing SPACES in front of FROM, Join, (SELECT etc... So when they are being output you are seeing FROM Products.ProductsJoin. You also want to prefix with # to protect against escaping issue. To fix you want:
y1.CommandText = #"Select [ID], [PartNumber], [Book], [HTMLDescription], [HTMLValueAdded], [RoHSCompliant], [ULCompliant],[CECompliant], [Series], [BUSINESS_UNIT], [ONEK], [FIVEK], [TENK], [TWENTYFIVEK]" +
",[Fifty], [OneHundred], [FiveHundred], [PACKAGING_TYPE], [PACK_QTY], [MOQ], [ORDER_MULTIPLE], [LEAD_TIME_WEEKS], [INTERNATIONAL_HARMONIZE_CODE], [ECCN_NUMBER], [COUNTRY_OF_ORIGIN]" +
",[IS_PART_STATIC_SENSITIVE], [IS_PART_LEAD_PB_FREE], [MOISTURE_SENSITIVITY_LEVEL_MSL], [REGISTERABLE], [TAPE_WIDTH], [TAPE_MATERIAL], [Reach138Compliant], [ConflictMinerals], [WebEnabled]" +
" FROM Products.Products" +
" Join" +
" (SELECT Products.Prices.ProductID," +
"Max(IIf(Products.Prices.Code='ONEK',Products.Prices.Price,Null)) AS ONEK," +
"Max(IIf(Products.Prices.Code='FIVEK',Products.Prices.Price,Null)) AS FIVEK," +
"Max(IIf(Products.Prices.Code='TENK',Products.Prices.Price,Null)) AS TENK," +
"Max(IIf(Products.Prices.Code='TWENTYFIVEK',Products.Prices.Price,Null)) AS TWENTYFIVEK," +
"Max(IIf(Products.Prices.Code='Fifty',Products.Prices.Price,Null)) AS Fifty," +
"Max(IIf(Products.Prices.Code='OneHundred',Products.Prices.Price,Null)) AS OneHundred," +
"Max(IIf(Products.Prices.Code='FiveHundred',Products.Prices.Price,Null)) AS FiveHundred" +
" FROM Products.Prices" +
" GROUP BY Products.Prices.ProductID" +
") As pp" +
" ON Products.Products.ID = pp.ProductID" +
" where partnumber like '6%'";
Just use verbatim string (#), copy your query and create it like:
string query =
#"Select
[ID]
,[ProductTypeID]
,[SeriesID]
,[PartNumber]
,[Title]
,[SEOFriendlyURLTitle]
,[HTMLDescription]
,[HTMLValueAdded]
,[RoHSCompliant]
,[ULCompliant]
,[CECompliant]
,[Series]
,[BUSINESS_UNIT]
,[PACKAGING_TYPE]
,[PACK_QTY]
,[MOQ]
,[ORDER_MULTIPLE]
,[LEAD_TIME_WEEKS]
,[INTERNATIONAL_HARMONIZE_CODE]
,[ECCN_NUMBER]
,[COUNTRY_OF_ORIGIN]
,[IS_PART_STATIC_SENSITIVE]
,[IS_PART_LEAD_PB_FREE]
,[MOISTURE_SENSITIVITY_LEVEL_MSL]
,[REGISTERABLE]
,[TAPE_WIDTH]
,[TAPE_MATERIAL]
,[QtyOnHand]
,[QtyOnSalesOrder]
,[QtyOnBackOrder]
,[ProductLine]
,[Reach138Compliant]
,[ConflictMinerals]
,[WebEnabled]
,[DateAdded]
,[UpdateDate]
,[Reviewed]
,[ReviewedBy]
,[Deleted]
,[Book]
,[CustomSort]
,[ONEK]
,[FIVEK]
,[TENK]
,[TWENTYFIVEK]
,[Fifty]
,[OneHundred]
,[FiveHundred]
FROM Products.Products
Join
(SELECT Products.Prices.ProductID,
Max(IIf(Products.Prices.Code='ONEK',Products.Prices.Price,Null)) AS ONEK,
Max(IIf(Products.Prices.Code='FIVEK',Products.Prices.Price,Null)) AS FIVEK,
Max(IIf(Products.Prices.Code='TENK',Products.Prices.Price,Null)) AS TENK,
Max(IIf(Products.Prices.Code='TWENTYFIVEK',Products.Prices.Price,Null)) AS TWENTYFIVEK,
Max(IIf(Products.Prices.Code='Fifty',Products.Prices.Price,Null)) AS Fifty,
Max(IIf(Products.Prices.Code='OneHundred',Products.Prices.Price,Null)) AS OneHundred,
Max(IIf(Products.Prices.Code='FiveHundred',Products.Prices.Price,Null)) AS FiveHundred
FROM Products.Prices
GROUP BY Products.Prices.ProductID
) As pp
ON Products.Products.ID = pp.ProductID";
(This will save you from figuring out errors in your concatenation, and would be more readable IMO)

How to Insert data into self reference table in sql server? [duplicate]

This question already exists:
Insert query for self reference of single table in sql server?
Closed 10 years ago.
What is the the query for inserting data into a self-referencing table. My table has 4 columns: SlNo, Name , ParentId , CurrentBanlance.
I tried this SQL query but it doesn't execute, is there any another way?
INSERT INTO Ptr_AcntInfo
SELECT
'" + txtAcName.Text + "',
(SELECT [SlNo] FROM Ptr_AcntInfo WHERE [Ac_Nm] = '" + cbxAcntGrpName.Text + "'),"+0.00+""
In this query I am getting the below error.
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The query should look like:
"INSERT INTO PTR_ACNTINFO (COL1, COL2)
(SELECT " + txtAcName.Text + ", SINo FROM
PTR_ACNTINFO
WHERE [Ac_Nm]='" + cbxAcntGrpName.Text + "')"
Note this query is vulnerable to SQL Injection attacks.
http://en.wikipedia.org/wiki/SQL_injection
You should use parameterised queries or a stored procedure.
Example:
SQLCommand sqlCommand = new SQLCommand(connection);
sqlCommand.CommandText = "INSERT INTO PTR_ACNTINFO (SELECT $name, SINo FROM
PTR_ACNTINFO WHERE [Ac_Nm]='$accNo')"
sqlCommand.Parameters.AddWithValue("$name", txtAcName.Text);
sqlCommand.Parameters.AddWithValue("$accNo", cbxAcntGrpName.Text);
http://johnhforrest.com/2010/10/parameterized-sql-queries-in-c/

Categories

Resources