Invalid column name SQL - c#

I have wasted hours trying to find what's incorrect in my code. Before adding a new column in the table, it was ok but after that, whenever I submit my form, it gives me an error
The column name is not valid. [ Node name (if any) = ,Column name = userID ]
Here is my code:
con.Open();
string query = "INSERT INTO PlayerTable
(username ,password, picture, scoreL1, scoreL2, scoreL3, userID)
VALUES
('" + #userName + "','" + #password + "',#picture," + #score1
+ "," + #score2 + "," + #score3 + "," + #num + ")";
cmd.Parameters.AddWithValue("#picture", a);
cmd.Parameters.AddWithValue("#username", userName);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#scoreL1", score1);
cmd.Parameters.AddWithValue("#scoreL2", score2);
cmd.Parameters.AddWithValue("#scoreL3", score3);
cmd.Parameters.AddWithValue("#userID", num);
cmd = new SqlCeCommand(query, con);
cmd.ExecuteNonQuery();

Shouldn't it be:
string query =
"INSERT INTO PlayerTable
(username, password, picture, scoreL1, scoreL2, scoreL3, userID)
VALUES(#userName, #password, #picture, #scoreL1, #scoreL2, #scoreL3, #userID)";
That is not #score1 but #scoreL1 and same for the others.
Edit
When you instantiate a new SqlCeCommand:
cmd = new SqlCeCommand(query, con);
you essentially erase the paramaters you set earlier.
Move the instantiation above the parameter assignments:
cmd = new SqlCeCommand(query, con);
cmd.Parameters.AddWithValue("#picture", a);
cmd.Parameters.AddWithValue("#username", userName);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#scoreL1", score1);
cmd.Parameters.AddWithValue("#scoreL2", score2);
cmd.Parameters.AddWithValue("#scoreL3", score3);
cmd.Parameters.AddWithValue("#userID", num);
cmd.ExecuteNonQuery();

You should not be surrounding your query parameters with quotes:
string query = "INSERT INTO PlayerTable
(username ,password, picture, scoreL1, scoreL2, scoreL3, userID)
VALUES(#userName, #password, #picture, #scoreL1, #scoreL2, #scoreL3, #userID )";
Additionally, you need to make sure your Parameter Names match the # values.

Related

How to check for duplicated Name before adding it to the database

Create to check for the duplicated name before being entered in the database)
private void btn_Submit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
if (txt_Name.Text == "Employee")
{
cmd.ExecuteNonQuery();
con.Close();
display_data();
MessageBox.Show("Name existed");
}
else
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Employee values('" + txt_Name.Text + "','" + txt_Contact.Text + "','" + txt_Address.Text + "','" + txt_Email.Text + "','" + txt_Password.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
display_data();
MessageBox.Show("Inserted successfully");
}
}
It is a security risk to concat the string with the parameters, use the sqlcommand parameters instead https://learn.microsoft.com/de-de/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=dotnet-plat-ext-6.0
Example:
var query = "INSERT INTO Employee VALUES (#name, #contact, #address, #email, #password)";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#contact", txt_Contact.Text);
cmd.Parameters.AddWithValue("#address", txt_Address.Text);
cmd.Parameters.AddWithValue("#email", txt_Email.Text);
cmd.Parameters.AddWithValue("#password", txt_Password.Text);
There are several ways to the goal for your problem
Unique Index
You can add an unique index on the table, this throws an exception when executing the command
Transact-SQL
It is also possible to move the whole verification logic to the database server
https://dba.stackexchange.com/questions/125886/check-if-a-user-exists-in-a-sql-server-database
IF NOT EXISTS (SELECT * FROM Employee WHERE Name = #name)
BEGIN
INSERT INTO Employee VALUES (#name, #contact, #address, #email, #password)
END
Query before insert
Execute a second query with a filter by name and check if a row exists. However, this is not an absolute protection. Duplicate data can still occur here with parallel executions.
If you start a transaction you could secure this block but this would restrict the database access for other users during this time. https://learn.microsoft.com/en-us/sql/relational-databases/sql-server-transaction-locking-and-row-versioning-guide?view=sql-server-ver16
You can get the number of rows with the same name. If it is greater than zero, do not add new row...
But the better way is to create a UNIQUE INDEX for the name column in sql like:
CREATE UNIQUE INDEX uidx_pid
ON Employee(name);
then on c# code:
string sqlQuery = "insert into Employee values('" + txt_Name.Text + "','" + txt_Contact.Text + "','" + txt_Address.Text + "','" + txt_Email.Text + "','" + txt_Password.Text + "')";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery , con))
{
try
{
con.Open();
cmd.ExecuteNonQuery();
display_data();
MessageBox.Show("Inserted successfully");
}
catch(Exception ex) {
display_data();
MessageBox.Show("Name existed");
};
}
}

How do I convert the result of ExecuteScalar() to int?

I am actually trying to get the primary key after the insertion by using ExecuteScalar(). Since it returns the first column of the first row after the insertion. But I am getting 0. I do not know why it is happening. Please help me out.
query = "Insert into Admissions(Admission_date, Student_name, Father_name, Mother_name, DOB, Gender, Address, State, City, Pincode, Admission_for, Previous_school, Fees) values ('" + txtAdmDate.Text + "','" + txtStudentName.Text + "','" + txtFatherName.Text + "','" + txtMotherName.Text + "','" + dob + "','" + gender + "','" + txtAddress.Text + "','" + txtState.Text + "','" + txtCity.Text + "','" + txtPincode.Text + "','" + cmbClass.Text + "','" + txtPreviousSchool.Text + "','" + txtFees.Text + "')";
cmd = new SqlCommand(query, con);
con.Open();
int admid = Convert.ToInt32(cmd.ExecuteScalar());
There are some issues with your code/question.
Your code is vulnerable to SQL Injection attacks. You need to parameterize your queries.
The INSERT statement by design is not meant to return anything, if you want to return the primary key of what you just inserted you need an output parameter in your query (better yet, a stored procedure).
A quick google for "return primary key on sql insert c#" would have given you a ton of results. Your question is asked almost verbatim here. In fact my answer is basically the top answers code (modified for your use).
Here is my answer
//Create an Admission class that represents your data
public static int Save(Admission admission)
{
var conn = DbConnect.Connection();
const string sqlString = "Admissions(Admission_date, Student_name, Father_name, Mother_name, DOB, Gender, " +
"Address, State, City, Pincode, Admission_for, Previous_school, Fees) values (#AdmissionDate, #StudentName, " +
"#FatherName, #MotherName, #DOB, #Gender, #Address, #State, #City, #Pincode, #AdmissionFor, #PreviousSchool, " +
"#Fees) SELECT SCOPE_IDENTITY()";
using (conn)
{
using (var cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.AddWithValue("#AdmissionDate", admission.AdmissionDate);
cmd.Parameters.AddWithValue("#StudentName", admission.StudentName);
cmd.Parameters.AddWithValue("#FatherName", admission.FatherName);
cmd.Parameters.AddWithValue("#MotherName", admission.MotherName);
cmd.Parameters.AddWithValue("#DOB", admission.DOB);
cmd.Parameters.AddWithValue("#Gender", admission.Gender);
cmd.Parameters.AddWithValue("#Address", admission.Address);
cmd.Parameters.AddWithValue("#State", admission.State);
cmd.Parameters.AddWithValue("#City", admission.City);
cmd.Parameters.AddWithValue("#Pincode", admission.Pincode);
cmd.Parameters.AddWithValue("#AdmissionFor", admission.AdmissionFor);
cmd.Parameters.AddWithValue("#PreviousSchool", admission.PreviousSchool);
cmd.Parameters.AddWithValue("#Fees", admission.Fees);
cmd.CommandType = CommandType.Text;
conn.Open();
return (int)(decimal)cmd.ExecuteScalar();
}
}
}
Try using an OUTPUT clause in your SQL command to return information about your command.
public int NewProperty(PropertyData propertyData)
{
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("InsertUpdateProperty", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", propertyData.ID);
cmd.Parameters.AddWithValue("#ListPropertyFor", propertyData.ListPropertyFor);
cmd.Parameters.AddWithValue("#PropertyTypeId", propertyData.PropertyTypeId);
cmd.Parameters.AddWithValue("#PropertyLoction", propertyData.PropertyLocation);
cmd.Parameters.AddWithValue("#Locality", propertyData.Locality);
cmd.Parameters.AddWithValue("#ProjectName", propertyData.ProjectName);
cmd.Parameters.AddWithValue("#PropertyDescription", propertyData.PropertyDescription);
cmd.Parameters.AddWithValue("#SuperBulidupArea", propertyData.SuperBulidupArea);
cmd.Parameters.AddWithValue("#SuperBulidupId", propertyData.SuperBulidupAreaId);
cmd.Parameters.AddWithValue("#BulidupArea", propertyData.BulidupArea);
cmd.Parameters.AddWithValue("#BulidupAreaId", propertyData.BulidupAreaId);
cmd.Parameters.AddWithValue("#CarpetArea", propertyData.CarpetArea);
cmd.Parameters.AddWithValue("#CarpetAreaId", propertyData.CarpetAreaId);
cmd.Parameters.AddWithValue("#Bathrooms", propertyData.Bathrooms);
cmd.Parameters.AddWithValue("#Bedrooms", propertyData.Bedrooms);
cmd.Parameters.AddWithValue("#Balconies", propertyData.Balconies);
cmd.Parameters.AddWithValue("#FurnishedId", propertyData.FurnishedId);
cmd.Parameters.AddWithValue("#TotalFloors", propertyData.TotalFloors);
cmd.Parameters.AddWithValue("#PropertyOnFloors", propertyData.PropertyOnFloor);
cmd.Parameters.AddWithValue("#Parking", propertyData.Parking);
cmd.Parameters.AddWithValue("#AvalibiltyId", propertyData.AvalibiltyId);
cmd.Parameters.AddWithValue("#AgeOfProperty", propertyData.AgeOfProperty);
cmd.Parameters.AddWithValue("#OwnerShip", propertyData.OwenerShip);
cmd.Parameters.AddWithValue("#Price", propertyData.Price);
cmd.Parameters.AddWithValue("#IsActive", propertyData.IsActive);
con.Open();
int i = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
return i;
}
}

Why is select scope_identity() returning 1 for SQL query?

I am using SQL query to with SELECT SCOPE_IDENTITY() in sqlcommand. here is my code:
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_Supplier(Supplier_Name,Supplier_Address, Supplier_PhoneNo,Supplier_City,Supplier_Remarks) VALUES('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','"+DropDownList1.SelectedItem+"','"+TextBox4.Text+"') RETURN SCOPE_IDENTITY()", conn);
var id = cmd.ExecuteScalar();
conn.Close();
but the code is always returning 1?
You are using the wrong syntax to get that info.
"...; SELECT SCOPE_IDENTITY()"
(Notice also the semicolon before the SELECT and after the end of the first sql statement)
At this point the ExecuteScalar is able to get the first column of the first row returned by the SELECT
Said that, please take a bit of your time to learn how to execute "Parameterized Queries" your code is very weak and an easy target for Sql Injection
string cmdText = #"INSERT INTO tbl_Supplier
(Supplier_Name,
Supplier_Address,
Supplier_PhoneNo,
Supplier_City,
Supplier_Remarks)
VALUES(#name, #address, #phone, #city, #remarks);
SELECT SCOPE_IDENTITY()"
using(SqlCommand cmd = new SqlCommand(cmdText, connection))
{
connection.Open();
cmd.Parameters.Add("#name", SqlDbType.NVarWChar).Value = TextBox1.Text;
cmd.Parameters.Add("#address", SqlDbType.NVarWChar).Value = TextBox2.Text;
cmd.Parameters.Add("#phone", SqlDbType.NVarWChar).Value = TextBox3.Text;
cmd.Parameters.Add("#city", SqlDbType.NVarWChar).Value = DropDownList1.SelectedItem
cmd.Parameters.Add("#remarks", SqlDbType.NVarWChar).Value = TextBox4.Text;
var id = cmd.ExecuteScalar();
}
conn.Close();

Unable to insert contents into the database

I have created a sql server database in godaddy and created a table named property manually.i also successfuly connected my application to the database using connection string.But i am unable to insert any values to the table using my c# code
Below is my C# code
string strQuery = "INSERT INTO property(name,email,phone,heading,description,location,image1,image2,image3,image4) VALUES('" + name + "','" + email + "','" + phone + "','" + title + "','" + description + "','" + district + "',#data,#data2,#data3,#data4);";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#data", SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add("#data2", SqlDbType.Binary).Value = bytes2;
cmd.Parameters.Add("#data3", SqlDbType.Binary).Value = bytes3;
cmd.Parameters.Add("#data4", SqlDbType.Binary).Value = bytes4;
SqlConnection con = new SqlConnection(constr);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
Parameterize your query and clean it up a bit. Hope this helps.
using (SqlConnection con = new SqlConnection("Connection Info"))
{
// Create your parameterized command.
SqlCommand cmd = new SqlCommand("INSERT INTO [property] (name, email, phone, heading, description, location, " +
" image1, image2, image3, image4) VALUES " +
" (#name, #email, #phone, #heading, #description, #location, " +
" ,#image1,#image2,#image3,#image4)", con);
using (cmd)
{
// Set your command type.
cmd.CommandType = CommandType.Text;
// Add your parameters.
cmd.Parameters.AddWithValue("#name", "nameParamHere");
cmd.Parameters.AddWithValue("#email", "emailParamHere");
// and so on until you complete all params.
// Execute your command.
using (SqlDataReader dr = cmd.ExecuteReader()) { };
}
}
Try granting insert to your connection string "USER ID". See this link for more info...
http://beginner-sql-tutorial.com/sql-grant-revoke-privileges-roles.htm
GRANT INSERT
ON [property]
TO {user_name}
[WITH GRANT OPTION];

How can I add auto numbering in visual c# 2010? using ms Access?

I'm using autonumber but it doesn't work for me. I want auto numbering in my StudentID number.
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText =
"insert into Student(ID, Lastname, Middlename, Firstname, Address, DateofBirth, Birthplace, Contact_number, emailaddress, guardian_name, Guardian_contact) values ('" + txtStudentIDnumber.Text + "','" + txtlastname.Text + "','" + txtfirstname.Text + "','" +
txtmiddlename.Text + "','" + txtaddress.Text + "','" + txtdateofbirth.Text + "','" + txtbirthplace.Text + "','" + txtcontactnumber.Text + "','" + txtemailaddress.Text + "','" + txtGuardianname.Text + "','" + txtguardiancontact.Text + "')";
system.Connection = mydatabase;
if (MessageBox.Show("Save data?", "Confirm Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
It is difficult to determine the issue without the database schema or the error message. However, the issue is probably because you are trying to insert a value into the ID column when it may have auto numbering (also known as a counter) enabled. Change:
system.CommandText = "insert into Student(ID, Lastname, ..."; // And so on
to
system.CommandText = "insert into Student(Lastname, ..."; // And so on
Also consider changing the query to be a parameterized query (such as that mentioned in incorrect syntax near 's'. unclosed quotation mark after the character string ')') rather than using concatenation to avoid SQL injection and escaping issues.
first you should specify identity Column like this :
then your code :
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\db.accdb");
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = string.Format("insert into Student(LastName,...) values('{0}',...)",txtLastName.Text.Trim(),...);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Your ID column should be setup to be an identity (in the database), then you should omit it from the insert.
http://forums.asp.net/t/1492834.aspx/1
UPDATE
I suspect your StudentIdNumber is an actual stateissued ID number, and what you're looking for is an identity field.
You'll need to add an identity column to your table, either using the table designer you used to create the table, or using a script
CREATE TABLE Student(
ID int identity,
StudentIdNo varchar(10),
Lastname varchar(10),
Firstname varchar(10),
Middlename varchar(10),
CONSTRAINT AutoIncrementTest_PrimaryKey PRIMARY KEY (ID)
)
This will be the format of your insert statement, notice there is no ID field
"INSERT INTO Student (StudentIdNo, Lastname, Firstname, Middlename) VALUES (?)"
...in your case, after adding a identity field
OleDbCommand comm = new OleDbCommand();
comm.CommandType = CommandType.Text;
comm.CommandText =
#"insert into Student(StudentIdNo, Lastname, Firstname, Middlename)
values (#StudentIdNo, #Lastname, #Firstname, #Middlename)";
comm.Parameters.AddWithValue("#StudentIdNo", txtStudentIdNo.Text);
comm.Parameters.AddWithValue("#Lastname", txtlastname.Text);
comm.Parameters.AddWithValue("#Firstname", txtfirstname.Text);
comm.Parameters.AddWithValue("#Middlename", txtmiddlename.Text);
comm.Connection = mydatabase;

Categories

Resources