protected void addItem_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string PID;
Button oButton = (Button)sender;
PID = oButton.CommandArgument.ToString();
int productId = Convert.ToInt32(PID);
Debug.Write(productId);
string email = (string)(Session["email"]);
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
}
When my query executes, I get an error
Invalid column name 'productId'
As you can see, I have converted a string into an integer variable, I have printed off the variable to check what it is returning. It does return a int as expected, but for some odd reason i can not insert into to my table. Any help would be great.
Hope productId is not the primary key of the basket table.
Then,instead of
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);
Modify like below
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( #productId,#email)", con);
cmd.Parameters.Add(new SqlParameter("#productId",productId );
cmd.Parameters.Add(new SqlParameter("#email",email );
Why suggested to modify is to avoid SQLInjection attack. If you are unaware about that please go through the below link and learn it
https://en.wikipedia.org/wiki/SQL_injection
Two issues here, number 1, and a big one, parameterize that query! You're opening yourself up to SQL injection attacks with code like that.
The second is that you're not actually passing in your productId variable, you're telling it to use the value for the productId column - which is also the column you're trying to insert into.
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values (#productId, #email)");
cmd.Parameters.AddWithValue("#productId", productId);
cmd.Parameters.AddWithValue("#email", email);
I can't stress enough how dangerous it is to dump user input into SQL that's going to be run directly on your database.
Related
I am trying to delete few rows by Username. But my sql query apparently not working right. instead of reading the column username, it looks for the name as a column...
Edit: What im trying to achieve is to remove rows with the username John Rose... but insead it says its looking for the column name John Rose
System.Data.SqlClient.SqlException: 'Invalid column name 'Jack Rose'.'
This code is in the checkout button. Im showing the whole code just incase the cause might be outide of the delete query code.
protected void Button1_Click(object sender, EventArgs e)
{
string Username = Session["Username"].ToString();
con.Open();
string query = "INSERT INTO GuestOrder (Order_Id, Username, Order_Date, GrandTotal) values (#Order_Id, #Username, #Order_Date, #GrandTotal)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Order_Id", Label_OrderId.Text);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Order_Date", Label_OrderDate.Text);
cmd.Parameters.AddWithValue("#GrandTotal", Label_Grand.Text);
cmd.ExecuteNonQuery();
con.Close();
string sql = "DELETE FROM Cart WHERE Username =" + Username+"";
con.Open();
SqlCommand cmd1 = new SqlCommand(sql, con);
cmd1.ExecuteNonQuery();
con.Close();
con.Dispose();
string strSQL = "SELECT * FROM GuestOrder";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet("orderdetails");
dt.Fill(ds, "order");
ds.WriteXml(Server.MapPath(#".\xml\orders.xml"));
Response.Redirect("SuccessfulOrder.aspx");
con.Close();
}
You should use this as below:
string sql = "DELETE FROM Cart WHERE Username = #Username";
You need to put username in single quotes as below
string sql = "DELETE FROM Cart WHERE Username = '" + Username+"'";
or You can use parameterized version of this query to avoid the sql injection as
below:
string sql = "DELETE FROM Cart WHERE Username = #Username";
I have tables Member and Office which use an auto-increment primary key, Member_Id and Office_Id. I am inserting data into the tables but would like to have primary key of the Member table inserted on the Office Table as a foreign key, so that a member is assigned to an office record. Please assist. Below is a snippet of my code for inserting the records but I just do not know how to link the two tables.
protected void capture()
{
string CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
conn.Open();
SqlCommand com = new SqlCommand();
SqlParameter myParam = new SqlParameter();
com.CommandText = "INSERT into Member(Appointment_Number, Initials, Surname, Designation) VALUES (#Appointment_Number, #Initials, #Surname, #Designation)";
com.Parameters.AddWithValue("#Appointment_Number", txtAppointmentNumber.Text);
com.Parameters.AddWithValue("#Initials", txtInitials.Text);
com.Parameters.AddWithValue("#Surname", txtSurname.Text);
com.Parameters.AddWithValue("#Designation", ddlDesignation.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
//Insert records into the office table
com.CommandText = "INSERT into Offices(Office_Number, Status, Building, Branch, Floor) VALUES (#Office_Number, #Status, #Building, #Branch, #Floor)";
com.Parameters.AddWithValue("#Office_Number", txtOffNo.Text);
com.Parameters.AddWithValue("#Status", ddlOStatus.Text);
com.Parameters.AddWithValue("#Building", ddlBuilding.Text);
com.Parameters.AddWithValue("#Branch", ddlBranch.Text);
com.Parameters.AddWithValue("#Floor", ddlFloors.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
if (IsPostBack)
{
Response.Redirect("~/Pages/MemberDetails.aspx");
}
}
}
I think, you want to set a relation between offices and members 1 to n.
So to do that, lets add officeid field in members table, insert the office record before the member and change the code like this;
protected void capture()
{
string CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
conn.Open();
SqlCommand com = new SqlCommand();
SqlParameter myParam = new SqlParameter();
//Insert records into the office table
com.CommandText = "INSERT into Offices(Office_Number, Status, Building, Branch, Floor) VALUES (#Office_Number, #Status, #Building, #Branch, #Floor)";
com.Parameters.AddWithValue("#Office_Number", txtOffNo.Text);
com.Parameters.AddWithValue("#Status", ddlOStatus.Text);
com.Parameters.AddWithValue("#Building", ddlBuilding.Text);
com.Parameters.AddWithValue("#Branch", ddlBranch.Text);
com.Parameters.AddWithValue("#Floor", ddlFloors.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
com.CommandText = "select max(Office_Id) from Offices";
int officeid = Convert.ToInt32(com.ExecuteScalar());
com.CommandText = "INSERT into Member(officeid,Appointment_Number, Initials, Surname, Designation) VALUES (#officeid,#Appointment_Number, #Initials, #Surname, #Designation)";
com.Parameters.AddWithValue("#officeid", officeid);
com.Parameters.AddWithValue("#Appointment_Number", txtAppointmentNumber.Text);
com.Parameters.AddWithValue("#Initials", txtInitials.Text);
com.Parameters.AddWithValue("#Surname", txtSurname.Text);
com.Parameters.AddWithValue("#Designation", ddlDesignation.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
if (IsPostBack)
{
Response.Redirect("~/Pages/MemberDetails.aspx");
}
}
}
Once you've inserted into your first table, using the same connection, SELECT SCOPE_IDENTITY() to get the auto-assigned identity value just created. You can then use that to insert into the second table.
Using SCOPE_IDENTITY() will ensure that you always get the id that you just created. If your system is being used by multiple users concurrently, you don't want to risk picking up the identity value created by another user that happened to be inserting data at the same time as you.
e.g. after your first insert:
com.CommandText = "SELECT SCOPE_IDENTITY()";
int my_id_just_created = Convert.ToInt32(com.ExecuteScalar());
The simplest way to do this is probably to insert your Office table first, get the scope identity, and put that in the FK of you member insert. To get the scope identity just use this syntax :
INSERT INTO YourTable
(val1, val2, val3 ...)
VALUES(#val1, #val2, #val3...);
SELECT SCOPE_IDENTITY();
Then you use com.ExecuteScalar() that will return you an Int with the PK of the Office table that you can use as the FK of the Member table.
I have a textbox form that students fill out about their general information such as first and last name, city, state, etc. Sometimes a student can't remember if they filled out the form before and it will lead to duplicate entries in the ms-access database. Ideally I would like the code to first search the ms-access database for a matching first name AND last name on the same record before insertion. If there's a record that matches on both the entered first and last name fields then a script would run and say something like, "A matching record already exists, would you like to continue?" Clicking "Yes" would enter the record into a new row, clicking "Cancel" would not enter it into the database at all.
I started this code but I'm not sure if it's the right direction, any guidance would be appreciated, thanks.
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
(This is where I am stuck)
}
}
Below is the current code for the submit button.
protected void btnSubmit_Click(object sender, EventArgs e)
{
{
//Preforms insert statement on click to allow additions to the database
DateTime CurrentDate;
CurrentDate = DateTime.Now;
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\sites\schoolinfo\students_dev\App_Data\Studentdb.mdb";
string cmdstr = "INSERT into StudentList(FName, LName, BDay, Gender, School, Grade, Address, APT, City, State, Zip, Email, Phone, CellPhone, ParentFName, ParentLName, ParentEmail) values(#FName, #LName, #BDay, #Gender, #School, #Grade, #Address, #APT, #City, #State, #Zip, #Email, #Phone, #CellPhone, #ParentFName, #ParentLName, #ParentEmail)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
{
con.Open();
}
//The following fields are added from the student information to the corresponding database fields
com.Parameters.AddWithValue("#FName", txtFirstName.Text);
com.Parameters.AddWithValue("#LName", txtLastName.Text);
com.Parameters.AddWithValue("#BDay", txtBirthDate.Text);
com.Parameters.AddWithValue("#Gender", ddlGender.Text);
com.Parameters.AddWithValue("#School", txtSchool.Text);
com.Parameters.AddWithValue("#Grade", txtGrade.Text);
//The following fields are added from the contact information to the corresponding database fields
com.Parameters.AddWithValue("#Address", txtAddress.Text);
com.Parameters.AddWithValue("#APT", txtApt.Text);
com.Parameters.AddWithValue("#City", txtCity.Text);
com.Parameters.AddWithValue("#State", ddlState.Text);
com.Parameters.AddWithValue("#Zip", txtZip.Text);
com.Parameters.AddWithValue("#Email", txtEmail.Text);
com.Parameters.AddWithValue("#Phone", txtPhone.Text);
com.Parameters.AddWithValue("#CellPhone", txtCellPhone.Text);
com.Parameters.AddWithValue("#ParentFName", txtParentFName.Text);
com.Parameters.AddWithValue("#ParentLName", txtParentLName.Text);
com.Parameters.AddWithValue("#ParentEmail", txtParentEmail.Text);
com.ExecuteNonQuery();
con.Close();
//End database connection
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Student has been successfully added!')", true);
}
}
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
// Add your #Fname and #LName parameters here
com.Parameters.AddWithValue("#FName", firstName);
com.Parameters.AddWithValue("#LName", lastName);
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
myReader.Read();
int count = myReader.GetInt32(0);
// return count > 0 or whatever to indicate that it exists
}
}
couple of things:
you can set in your table the first name and last name as 1 primary key (yes it possible in ms-access). this way you will NEVER get any duplicate records
count(*) is not the best practice with databases.. but since you are dealing with ms-access
using (OleDbDataReader myReader = com.ExecuteReader())
{
// reads the first and only column count(*) and convert it to a number
if (Convert.ToInt16(myReader[0]) > 0)
{
// an entry already exists
}
}
You should use ExecuteScalar when the return value of your query is only a single row with a single column. Of course the OleDbCommand that has parameters placeholders in its command text needs to have also a corresponding Parameters collection
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
con.Open();
com.Parameters.AddWithValue("#FName", txtFirstName.Text);
com.Parameters.AddWithValue("#LName", txtLastName.Text);
int count = Convert.ToInt32(com.ExecuteScalar());
if(count == 0)
{
... record doesn't exist
}
else
{
... you have got count records
}
}
However let me say that this logic is rather weak. What happen if two students have the same First and Last name? What happen if someone mistype the name?. I think that you should require something more unique. Like a SSN or another ID provided by your school. (A Student Number or something alike)
if (txtYear.Text != "")
{
cmd = new SqlCommand("Select YearName from Year where YearName='" + txtYear.Text + "'", ConnOpen());
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if (i > 0)
{
MessageBox.Show("Duplicate Values are not valid!!!");
}
else
{
if (Classes.ClassDatabaseConnection.UserMessage("Are you srue you want to Add this Year!!!", "Confirm Updation") == true)
{
string insert = "insert into Year(YearName) values('" + txtYear.Text + "')";
int result = sqlrep.ExecuteNonQuery(insert);
if (result > 0)
{
System.Windows.Forms.MessageBox.Show("Year Added Successfully.", "Information", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
}
}
dataLoad();
}
}
I have been through everything for a couple weeks now only to find statements working at the database level. Below is my code and I feel that I am very near the answer but keep getting -1 returned from SCOPE_IDENTITY(). Customer_Name is saving to the table just fine along with the auto increment. I just need the Customer_ID so that I can place it in the Customer_Address table for the one to many identification of the address to the customer.
Thanks in advance for your help.
if (customer_ID == "")
{
// add new customer
string SQL = "INSERT INTO Customer (Customer_Name) VALUES (#customer_Name)";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add("#customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
// get last inserted Customer_ID
string SQL_customerId = "SELECT SCOPE_IDENTITY()";
SqlCommand sqlCommand_customerId = new SqlCommand(SQL_customerId, sqlConnection);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlCommand_customerId.ExecuteNonQuery();
// string SQL_ = "SELECT Customer_ID FROM Customer";
// SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
// int maxId = Convert.ToInt32(sqlCommand.ExecuteScalar());
sqlConnection.Close();
}
You need to have the SCOPE_IDENTITY within the same transaction as your insert. The following should help you.
string SQL = "INSERT INTO Customer (Customer_Name) VALUES (#customer_Name); SELECT Customer_Id FROM Customer WHERE Customer_Id = SCOPE_IDENTITY();";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add("#customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
sqlConnection.Open();
int id = (int) sqlCommand.ExecuteScalar();
try something like this..
Output clause will help you to get the inserted value and with that we can insert into another temp or physical table. This is just an idea to your question
CREATE TABLE customer
(
id INT IDENTITY(1, 1),
addres VARCHAR(500)
)
CREATE TABLE customeraddrs
(
custid INT
)
INSERT INTO customer
output inserted.id
INTO customeraddrs
VALUES ('a'),
('b')
SELECT *
FROM customer
SELECT *
FROM customeraddrs
I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. So how can I insert only to name, not id because id is auto increment?
I tried this
insert into student(id, name) values(,name)
but it is not insert to my table.
This is my code :
protected void Button1_Click(object sender, EventArgs e)
{
string test = txtName.Text;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");
string sql = "insert into student(name) values ('test')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
INSERT INTO student (name) values ('name')
Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.
You better use parameters when you insert data.
try
{
string sql = "insert into student(name) values (#name)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#name", test); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
You don't need to mention the ID in first part.
insert into student(name) values('name')
I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows:
commands executed in command shell of mssql like:
insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")
go
or
insert into table_name VALUES ("val1","val2",0,"val4")
go
work when typed directly in the mssql database prompt,
But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in:
SqlConnection cnn;
string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
cnn = new SqlConnection(connetionString);
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
//or
//SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
cnn.Open();
myCommand.ExecuteNonQuery();
cnn.Close();
the problem here is that most people, like myself, try to use <\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this.
Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation, where a string concatination looks like a feasible solution, like in:
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
Try the following query,
insert into student(name) values(name)
SQL Server internally auto increments the id column when u insert the data since u said it is auto increment. If it is not working, the u have to check the identity column in the db.
use the key word "identity" to auto increment the id column
Refer : http://technet.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
create table table_name( id int PRIMARY KEY IDENTITY )
and you no need to mention the "id" in the insert query