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

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.

Related

Join Table sql windowsForms

I would like to insert a record into table RDV .
The query of creation RDV Table:
CREATE TABLE [dbo].[RDV] (
[idRdv] INT NOT NULL,
[objet] NVARCHAR (50) NULL,
[objectif] NVARCHAR (50) NULL,
[DateRdv] DATETIME NULL,
[commentaire] NVARCHAR (50) NULL,
[archive] NVARCHAR (50) NULL,
[idClient] INT NULL,
[idUser] INT NULL,
[idResultat] INT NULL,
CONSTRAINT [PK_RDV] PRIMARY KEY CLUSTERED ([idRdv] ASC),
FOREIGN KEY ([idClient]) REFERENCES [dbo].[Client] ([idClient]),
FOREIGN KEY ([idUser]) REFERENCES [dbo].[User] ([idUser]),
FOREIGN KEY ([idResultat]) REFERENCES [dbo].[Resultat] ([idResultat])
There is here my code :
private void btnAdd_Click(object sender, EventArgs e)
{
SqlDataAdapter sda = new SqlDataAdapter("Insert into RDV (objet,objectif,DateRdv,commentaire,idClient)Select'" + textBox1.Text + "','" + textBox2.Text + "','" + dateTimePicker1.Text.ToString() + "','" + textBox4.Text + "',idClient from RDV where Client.idClient=RDV.idClient and idClient='"+comboBox2.SelectedValue+"'", con);
sda.SelectCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show("Le RDV a été ajouté avec succés !");
}
The Error was: The multi-part identifier " Client.idClient " can not be bound.
My syntax query it's wrong ??? if yes , how should I correct it .
Thanks in advance.
Well as the error says there is no reference to the Client table in your query, so it won't find the identifier Client.idClient. Either use a join or put Client in your From.
One problem is Insert syntax.
Insert into RDV ("table columns")
Values ("values")
Example: (http://www.w3schools.com/sql/sql_insert.asp)
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');

How can I insert into the table using SQL Server

I am stuck in this condition unable to insert into the table tbl_customer its giving error :
Arithmetic overflow error converting expression to data type int.
The statement has been terminated.
here is my table structure:
create table tbl_customer(
id int identity primary key,
cust_name varchar(50) NOT NULL,
filecode varchar(20) NOT NULL,
cust_mobile int,
cust_cnic varchar(50) NOT NULL,
cust_phone int,
cust_address varchar(200)
)
and here is the code i use to insert:
insert into tbl_customer values('Jonah Gordian','LHR001',03451119182,'11-22112-122',1212121212,'abc street 12')
and I used this code in c# to try inserting:
connclass.insert("insert into tbl_customer(cust_name,filecode,cust_mobile,cust_cnic,cust_phone,cust_address) VALUES('" + txtname.Text + "','" + txtfilecode.Text + "','" + int.Parse(txtmob.Text) + "','" + txtcnic.Text + "','" + int.Parse(txtphone.Text) + "','" + txtaddress.Text + "')");
create table tbl_customer(
id int identity primary key,
cust_name varchar(50) NOT NULL,
filecode varchar(20) NOT NULL,
cust_mobile varchar(20),
cust_cnic varchar(50) NOT NULL,
cust_phone varchar(20),
cust_address varchar(200)
)
insert into tbl_customer
(cust_name, filecode, cust_mobile, cust_cnic, cust_phone, cust_address )
values
('Jonah Gordian','LHR001','03451119182','11-22112-122','1212121212','abc street 12');
And also C# code is open to SQL injection attack, use parameters instead. ie:
string sql = #"insert into tbl_customer
(cust_name,filecode,cust_mobile,cust_cnic,cust_phone,cust_address)
VALUES
(#cust_name,#filecode,#cust_mobile,#cust_cnic,#cust_phone,#cust_address)";
using (SqlConnection con = new SqlConnection(#"server=.\SQLExpress;database=yourDbName;Trusted_Connection=yes"))
{
var cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#cust_name", txtname.Text);
cmd.Parameters.AddWithValue("#filecode", txtfilecode.Text);
cmd.Parameters.AddWithValue("#cust_mobile", txtmob.Text);
cmd.Parameters.AddWithValue("#cust_cnic", txtcnic.Text);
cmd.Parameters.AddWithValue("#cust_phone", txtphone.Text);
cmd.Parameters.AddWithValue("#cust_address", txtaddress.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
You define cust_mobile as int, but try to insert 03451119182, which is clearly over the limit of 2147483647.
Change to bigint or store as a VarChar (including the leading zero).
Try like this,
CREATE TABLE tbl_customer (
id INT identity PRIMARY KEY
,cust_name VARCHAR(50) NOT NULL
,filecode VARCHAR(20) NOT NULL
,cust_mobile BIGINT --or Varchar(20)
,cust_cnic VARCHAR(50) NOT NULL
,cust_phone INT
,cust_address VARCHAR(200)
)
INSERT INTO tbl_customer
VALUES (
'Jonah Gordian'
,'LHR001'
,03451119182
,'11-22112-122'
,1212121212
,'abc street 12'
)
You have exceeded the int datatype limit. Change the datatype from int to either bigint or Varchar to resolve the issue.
Note: If you need leading Zeros then you can choose Varchar otherwise you can make use of BigInt.
You exceeded the limit of the int try with bigint
this value 3451119182
see in this link the limits
https://msdn.microsoft.com/pt-br/library/ms187745(v=sql.120).aspx

Write SQL code similar to a stored procedure inside my MVC project

I am looking into rewriting a stored procedure that returns an output parameter inside my code. Why I am doing this is because I am wanting to have a local stored procedure instead of having to call the stored procedure from MSSQL.
Is this possible? If so, then how?
I have looked into LINQ to Entities and started to realize that there is so little control of the queries. I need to find more definitive info, but from working with real stored procedures and using multiple queries, having an actual stored procedure would be more efficient with large amounts (meaning hundreds of thousands) of records because of pre-built items included with MSSQL and SPs. I am using this question as a reference for a future project when we want to have small-scale data being transferred from the front end of the site instead of using stored procedures.
This link is what I used to write my raw SQL code. I am using the primitive calls so I can return string variables.
http://www.entityframeworktutorial.net/EntityFramework4.3/raw-sql-query-in-entity-framework.aspx
A rough draft of my stored procedure looks like this:
I am using // for legibility purposes when viewing this answer. Please use -- when using this code.
CREATE PROCEDURE [dbo].[spSomething]
#FirstName varchar(25),
#LastName varchar(25),
#UserID varchar(25),
#RentalManID varchar(25),
#BranchAreaNum varchar(25),
#ReturnVal varchar(1) = '0' output
WITH RECOMPILE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #CheckTblUserAdded varchar(25)
DECLARE #CheckTblUser varchar(25)
// ReturnVal = 0 means it failed to add user to table
// ReturnVal = 1 means it succeded in adding user to table
// ReturnVal = 2 means the user has already been added to the table
// Search for user inside tblUserAdded
SELECT #CheckTblUserAdded = [Window ID] FROM dbo.tblUserAdded WHERE [Window ID] = #UserID AND
[Rentalman ID] = #RentalManID AND
[BranchAreaNum] = #BranchAreaNum AND
[FirstName] = #FirstName AND
[LastName] = #LastName
// Search for user inside tblUser
SELECT #CheckTblUser = [UserID] FROM dbo.tblUser WHERE [UserID] = #UserID AND
[RentalManID] = #RentalManID
// Add new user if not found in either tblUserAdded or tblUser
// and if the users windows id and rentalmanid are not the same
IF (ISNULL(#CheckTblUserAdded, '') = '') AND (ISNULL(#CheckTblUser, '') = '') AND (#UserID <> #RentalManID)
BEGIN
// Do something here
SELECT #ReturnVal = '1' // as success
END
// Record attempt of adding an existing user
ELSE
BEGIN
// Do something here
SELECT #ReturnVal = '2' // already exists
END
SELECT #ReturnVal
END
This is my raw SQL version of this inside my controller:
public ActionResult Create([Bind(Include="Window_ID,Rentalman_ID,BranchAreaNum,FirstName,LastName")] tblUserAdded tbluseradded)
{
if (ModelState.IsValid)
{
if (tbluseradded.Window_ID == tbluseradded.Rentalman_ID)
{
System.Diagnostics.Debug.WriteLine("The user should already have access since the user's Windows ID and RentalMan ID are the same. Contact IAUnit for help on the issue");
}
else
{
// Rewrite stored procedure in form of raw SQL
string returnVal = "0";
// This will check to see if a user has already been added to tblUser and tblUserAdded
string checkTblUserAdded = db.Database.SqlQuery<string>("SELECT [Window ID] FROM dbo.tblUserAdded WHERE " +
"[Window ID] = '" + tbluseradded.Window_ID + "' AND " +
"[Rentalman ID] = '" + tbluseradded.Rentalman_ID + "' AND " +
"[BranchAreaNum] = '" + tbluseradded.BranchAreaNum + "' AND " +
"[FirstName] = '" + tbluseradded.FirstName + "' AND " +
"[LastName] = '" + tbluseradded.LastName + "'").FirstOrDefault<string>();
string checkTblUser = db.Database.SqlQuery<string>("SELECT [UserID] FROM dbo.tblUser WHERE " +
"[UserID] = '" + tbluseradded.Window_ID + "' AND " +
"[RentalManID] = '" + tbluseradded.Rentalman_ID + "'").FirstOrDefault<string>();
// Add new user if not found in either tblUserAdded or tblUser
if (checkTblUser == null && checkTblUserAdded == null)
{
System.Diagnostics.Debug.WriteLine("We can add the user now! We did it!");
returnVal = "1";
// Do something here
}
else
{
System.Diagnostics.Debug.WriteLine("This user already has access");
returnVal = "2";
// Do something here
}
System.Diagnostics.Debug.WriteLine("The return value is: " + returnVal);
System.Diagnostics.Debug.WriteLine("Please break here!");
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(tbluseradded);
}
I am sure there is a better way of coding this by putting the actual raw SQL in a Data Access Layer, but I am using this for information purposes only.

using C# for creating a stored procedure

I want to define one stored procedure having 2 tables that insert into the first table and updates the second table. The first table contains the PostID and the PersonID, the second table contains postID and Counter. Would you please help me correct this one? I know this is not correct.
com.CommandText = #"CREATE PROCEDURE dbo.Facebook #PostID int,#PerosnalID int,
BEGIN
INSERT dbo.Like (PostID) VALUES (#PersonalID),
UPDATE dbo.Counter (Counter)
SET PostID = #value1
WHERE Counter = Sum #PersonalID
END";
Let's start and fix the procedure syntax:
com.CommandText = "CREATE PROCEDURE dbo.Facebook( #PostID int,#PersonalID int) AS "+
" INSERT dbo.[Like] (PostID) VALUES (#PersonalID); " +
" UPDATE C SET Counter = (SELECT COUNT(*) FROM dbo.[Like] WHERE PostId = #PersonalID)" +
" FROM dbo.Counter AS C " +
" WHERE C.PostID = #PersonalID ";

how to insert from different inputs

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')

Categories

Resources