Foreign Keys constraint is not working in SQlite - sqlite

I am dropping pk from table 1 to table 2 as foreign key in my database using sqlite. But my table 2 is not working accordingly to foreign key constraint it is inserting record if that key is not available in table1. I am using db browser and my pragma foreign key is enabled there but its still not working

I have found the solution. You have to enable pragma foreign keys in your C# code everytime you make a connection.
Let me share my code:
conn.Open();
string query = " insert into Installment_Details (Account_No,Month_yr,Date,Receipt_No,Amount_Received,Amount_Left,Amount_receiver) values ('" + this.Textbox_AN.Text + "','" + this.Textbox_MY.Text + "','" + this.Textbox_D.Text + "','" + this.Textbox_RN.Text + "','" + this.Textbox_AR.Text + "','" + this.Textbox_AL.Text + "','" + this.Textbox_ARR.Text + "');";
SQLiteCommand createcommand = new SQLiteCommand("PRAGMA foreign_keys = ON", conn);
createcommand.ExecuteNonQuery();
createcommand = new SQLiteCommand(query, conn);
createcommand.ExecuteNonQuery();
MessageBox.Show("Saved Successfully");

It is not necessary to turn the pragma on in here:
SQLiteCommand createcommand = new SQLiteCommand("PRAGMA foreign_keys = ON", conn);
but better to turn it on when the connection is created:
ConnectionString = $"Data Source={databaseFile}; foreign keys=true";
connection = new SQLiteConnection(ConnectionString);
and then create the command and call the ExecuteNonQuery().

Related

'Parameters supplied for object 'AdminAssistant' which is not a function. If the parameters are intended as a table hint, a WITH keyword is required.'

While inserting values into the database i am getting error which is said in subject dont know what i am missing.
string ImagePath = "";
string str = "insert into AdminAssistant() values('"+TextBox7.Text+ "','" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + DropDownList2.Text + "','" + TextBox4.Text + "','" + DropDownList1.Text+ "','" + TextBox9.Text + "','"+ImagePath+"','"+DateTime.Now+"','Active')";
SqlCommand cmd = new SqlCommand(str,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Admin Created Successfully.....!!!";
Below is the Query
Create Table AdminAssistant
(
A_ID int identity(1,1) not null primary key,
Aname varchar(20),
Aphone varchar(16),
Amail varchar(20),
A_Address varchar(150),
A_City varchar(20),
A_Gender varchar(10)NOT NULL CHECK (A_Gender IN('Male', 'Female')),
A_Password varchar(20),
Aroll varchar(20)NOT NULL CHECK (Aroll IN('SuperAdmin', 'Admin')),
MetaDescription varchar(256),
Media varchar(40),
RegisterDate datetime,
A_Status varchar(20)NOT NULL CHECK (A_Status IN('Active', 'Disable'))
)
I think this values should inserted into database despite that it is giving error.
The error is probably caused by the presence of the parenthesys after the name of the table, but this is a simple fix to do.
Your real problem lies in the string concatenation for your values.
This is a no-no in the sql world because it could be the source of many parsing bugs (for example, the presence of a single quote in the values could break the syntax and DateTime.Now is converted to a string following rules the not always are understood by the sql parser engine).
But most important is the possibility of Sql Injection.
Here some links to start your discovery for this big security risk
How can I explain Sql Injection without technical jargon.
How does the SQL injection from the “Bobby Tables” XKCD comic work?
So the only fix is through a parameterized query.
string str = "insert into AdminAssistant
(Aname,Aphone,Amail,A_Address,A_City,A_Gender,A_Password,
Aroll,MetaDescription,Media,RegisterDate,A_Status)
values(#name,#phone,#mail,#address,#city,#gender,#pass
#roll,#descr,#media,#regdata,'Active')";
using(SqlConnection con = new SqlConnection(......))
using(SqlCommand cmd = new SqlCommand(str, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = TextBox7.Text;
... other varchar parameters
cmd.Parameters.Add("#regdataq", SqlDbType.DateTime).Value = DateTime.Now;
... complete the parameters collection
cmd.ExecuteNonQuery();
}
And, I have forget to talk about storing passwords in clear text into a database. This is another very important consideration for your security. Here another link with useful info
Best way to store password in database

error Incorrect syntax near ','

SqlConnection con = new SqlConnection(#"Data Source=shashi-PC\SQLEXPRESS;Initial Catalog=payroll;Integrated Security=True;Pooling=False");
SqlCommand com = new SqlCommand("insert into Leave_trans values(" + txtempid.Text + ",'" + ddlleavetype.SelectedValue + "'," + txtallowedays.Text + "," + txtpendingleave.Text + ",'" + txtleavefrom.Text + "','" + txtleaveto.Text + "'," + txttotalleaves.Text + ")");
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
Response.Write("<script>alert('Leave data saved successfully')</script>");
con.Close();
This doesn't directly answer your question, but you should never take user-input and use string concatenation to build an SQL query (please take some time to read about SQL injection e.g. here or here).
Instead of concatenating the full query, you should use SqlParameter instances as placeholders for your values, e.g:
var com = new SqlCommand(
"insert into Leave_trans values(#empId, #leaveType, #allowedDays, ...)");
com.Parameters.Add(new SqlParameter("#empId", txtempid.Text));
com.Parameters.Add(new SqlParameter("#leaveType", ddlleavetype.SelectedValue));
com.Parameters.Add(new SqlParameter("#allowedDays", txtalloweddays.Text));
...
BTW: the cause for your problem is that you are not correctly single-quoting your inputs inside the query (e.g. txtempid.Text is not in single quotes). Using SqlParameters will also solve that problem for you.
I think the problem is in your query. You didn't provide us the data type of your database columns. But assuming from your query you are inserting some text from TextBox and one DropDownList selected item. From your TextBox text you will always get a string type value and for inserting string into your columns you should use single quotation '' before and after on it. But on your query you didn't use any quotation for some of your value parameter. I made an assumption and made a query for you. try this updated one.
SqlConnection con = new SqlConnection(#"Data Source=shashi-PC\SQLEXPRESS;Initial Catalog=payroll;Integrated Security=True;Pooling=False");
SqlCommand com = new SqlCommand("insert into Leave_trans values(" + "'" + txtempid.Text + "'", "'" + ddlleavetype.SelectedValue + "'","'" + txtallowedays.Text + "'","'" + txtpendingleave.Text + "'", "'" + txtleavefrom.Text + "'","'" + txtleaveto.Text + "'", "'" + txttotalleaves.Text + "')");
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
Response.Write("<script>alert('Leave data saved successfully')</script>");
But i have some suggestion for you that is- you shouldn't use string as your table's primary key data type, it should be int type and another one is you should take int id of your selected item from your DropDownList not the text.

How to RETURN #Identity of instert data in spl in asp.net

I'm inserting data in a table with this code below.
SqlCommand cmd = new SqlCommand("INSERT INTO Users (Username,Password,FirstName,lastName,PhoneNumber,Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)"
+ ("VALUES ('" + TextBox1.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "','User','0','" + Date + "')"), con);
cmd.ExecuteNonQuery();
I want to get Id of inserting Value in database which I save new data in table anyone have any idea what can i have to add in a code so i can RETURN #Identity of insert value in table and use that id some other code.
Thank you
First use parametrized queries (to avoid SQL Injection attack)
var sql = "INSERT INTO Users (Username,Password,FirstName,lastName,PhoneNumber,Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)" +
"values (#username, #password, #firstname, #lastname, #phone, #address, #city, #state, #country, #zipcode, #usertype, #payout, #timedate);" +
"select SCOPE_IDENTITY()";
var cmd = new SqlCommand(sql);
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox3.Text);
cmd.Parameters.AddWithValue("#firstname", TextBox4.Text);
cmd.Parameters.AddWithValue("#lastname", TextBox5.Text);
cmd.Parameters.AddWithValue("#phone" TextBox6.Text);
//and so on
var id = Convert.ToInt32(cmd.ExecuteScalar());
SCOPE_IDENTITY returns last id created for inserted row in given scope. This way you get back id. Use ExecuteScalar() method that returns one value from first row, first column.
Also do not store clear text as password, use some hashing method.
change your sql and code like as below
for sql 2005+
INSERT INTO Users (UserId,otherdata...)
OUTPUT INSERTED.ID
VALUES(#UserId, #othervalues...)
for sql 2000
INSERT INTO aspnet_GameProfiles(UserId,otherdata...)
VALUES(#UserId, #othervalues...);
SELECT SCOPE_IDENTITY()
And then
Int32 newId = (Int32) myCommand.ExecuteScalar();
Suggestion:
Make use of parameterize query to avoid sql injection attack....
The simplest way would be to append "SELECT SCOPE_IDENTITY()" to your SQL statement. You should parametrize your query to avoid SQL Injection, and it would look something like:
string sql = #"
INSERT INTO Users
(Username,Password,FirstName,lastName,PhoneNumber,
Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)
VALUES(#Username, #Password, ...)
SELECT SCOPE_IDENTITY()
";
SqlCommand cmd = new SqlCommand(sql, ...);
... append parameters ...
var identity = (decimal) cmd.ExecuteScalar();
If your identity column is an integer, you can either cast from decimal to integer, or do the cast in SQL Server, e.g.
string sql = #"
INSERT INTO Users
...
SELECT CAST(SCOPE_IDENTITY() AS INT)
";
SqlCommand cmd = new SqlCommand(sql, ...);
... append parameters ...
var identity = (int) cmd.ExecuteScalar();
Note that SCOPE_IDENTITY is generally a better choice than ##IDENTITY. In most cases, they will return the same value. But, for example, if your INSERT statement causes a trigger to fire, which inserts an identity value in a second table, then it's the identity value inserted into this second table that will be returned by ##IDENTITY. Using SCOPE_IDENTITY avoids this problem.

Insert dynamic data in phonegap sqlite?

I have developed one app using phonegap. I want to insert the data using the phonegap sqlite. I have got the bulk of data from server using web service. Now I want to insert the service response data into local database.
for(var i=0;i<serviceResponse.length;i++)
{
var insertQuery = "";
insertQuery = "INSERT INTO PREFERENCE(ID,NAME,TYPE,VALUE,ISFAVORITE,RANK) VALUES (" + "'" + serviceResponse[i].prefid + "','" + serviceResponse[i].name + "','" + serviceResponse[i].type+ "','" + serviceResponse[i].ispreference+ "','" +serviceResponse[i].isfavorite+ "','"+serviceResponse[i].rank + "')" ;
dbinsert.transaction(function insertUserPrefDB(tx){
tx.executeSql(insertQuery);
},errorCB);
if(i==(serviceResponse.length-1))
{
alert("Pref Inserted Successfully");
}
}
What is my problem here is,
This code will insert the last record in local database. If the service response having 10 records that time the local db also having 10 records but all records are same (i.e.last record return from service).
Please help me.

How to insert a row with "autonumber" field (ID column) into Access Database/ C# ASP.NET [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
This is my first time working with DB.
I've decided to create a DB with two tables - "Team", "Player"
I want to add a new player to the "Player" table.
The "Player" table consists of the following columns: ID(autonumber), FirstName, LastName, TeamID
In order to do so, I've created three text boxes for the FirstName, LastName, TeamID
Note that I did not treat the "ID" since it's an autonumber and should be added automatically
The Button1_click should add the new row eventually.
Here's my code:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
connection = new OleDbConnection(connectionString);
}
catch
{ }
try
{
connection.Open();
OleDbCommand command = new OleDbCommand("INSERT INTO Player VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')");
command.ExecuteNonQuery();
connection.Close();
}
catch
{ }
When you write an INSERT string that doesn't include the column names you should specify every column in the values. In your case you need to add
string sqlText = "INSERT INTO Player (FirstName, LastName, TeamID) VALUES ('"
+ TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')");
However this code is wrong for another reason. Never write sql strings concatenating input text typed by the user. This will cause errors or, worse, lead to Sql Injection
using(connection = new OleDbConnection(connectionString))
{
connection.Open();
string sqlText = "INSERT INTO Player (FirstName, LastName, TeamID) " +
"VALUES (?, ?, ?)";
OleDbCommand command = new OleDbCommand(sqlText, connection);
command.Parameters.AddWithValue("#First", textBox1.Text);
command.Parameters.AddWithValue("#Last", textBox2.Text);
command.Parameters.AddWithValue("#team", textBox3.Text);
command.ExecuteNonQuery();
}
There is another problem. If the TeamID field is a numeric field you need to convert the textbox3.text input in a numeric value to correctly use the AddWithValue method
int teamID;
if(!Int32.TryParse(textBox3.Text, out teamID))
throw new ArgumentException("Type a valid TeamID number, please!");
command.Parameters.AddWithValue("#team", teamID);
If TeamID is a number, you don't need quotes around it.
OleDbCommand command = new OleDbCommand("INSERT INTO Player VALUES ('" + TbFirstName.Text + "','" + TbLastName.Text + "'," + TbTeamID.Text + ")");
Note: I renamed the textboxes to reduce ambiguity.
While this is probably your first pass at this, you should really sanitize your inputs. At the bare minimum create a function to replace single quotes with a double single quote.
protected string SanitizeSQL(string txt) {
return txt.replace("'", "''");
}
OleDbCommand command = new OleDbCommand("INSERT INTO Player VALUES ('" + SanitizeSQL(TbFirstName.Text) + "','" + SanitizeSQL(TbLastName.Text) + "'," + SanitizeSQL(TbTeamID.Text) + ")");
Your insert command should specify the columns it's updating, so it should be:
INSERT INTO Player(FirstName,LastName,TeamID) VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')"
Also note that concatenating text from user input directly into a query opens you up to sql injection attacks.

Resources