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;
}
}
Related
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");
};
}
}
The values staring vith cmb is a combo box. When I click the save button, it throws an error.
My code is here:
cn.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = cn;
command.CommandText = "insert into TblProductDetails(ProductID, ProductName, Category, Section, UOM, CostPrice, SellingPrice1, SellingPrice2, DiscountPercentage, DiscountAmount, MinimumPrice, Vendor, Stock) values ('" + txtProductID.Text + "','" + txtName.Text + "','" + category + "','" + section + "','" + uom + "','" + txtCostprice.Text + "','" + txtSellingPrice1.Text + "','" + txtSellingPrice2.Text + "','" + txtDiscountpercentage.Text + "','" + txtDiscountAmount.Text + "','" + txtMinimumPrice.Text + "','" + vendor + "','" + txtBeginingStock.Text + "')";
command.ExecuteNonQuery();
cn.Close();
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Your DataBasePath";
conn.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO TblProductDetails (ProductID, ProductName, Category, Section, UOM, CostPrice, SellingPrice1, SellingPrice2, DiscountPercentage, DiscountAmount, MinimumPrice, Vendor, Stock) VALUES(#ProductID, #ProductName, #Category, #Section, #UOM, #CostPrice, #SellingPrice1, #SellingPrice2, #DiscountPercentage, #DiscountAmount, #MinimumPrice, #Vendor, #Stock)";
cmd.Parameters.AddWithValue("#ProductID", comboBox1.Text);
cmd.Parameters.AddWithValue("#ProductName", textBox1.Text);
cmd.Parameters.AddWithValue("#Category", textBox2.Text);
cmd.Parameters.AddWithValue("#Section", textBox2.Text);
cmd.Parameters.AddWithValue("#UOM", textBox4.Text);
// continue Your Code its just example
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
It could be many things. See comment from Steve. But you also want to check the values in the text boxes for the " ' " character (apostrophe) as if the text box contains that character then that could also cause syntax issues, check out SQL injection for more information on that. Thought this was worth a mention. You could use a DataTableAdapter for this kind of thing too, or Entity Framework just to clear that up a little (I would do).
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SAGAR\\SQLEXPRESS;Initial Catalog=ClinicDb;Integrated Security=True");
con.Open();
SqlCommand sc = new SqlCommand("insert into Patient_Details (Patient Id,Name,Age,Contact No,Address) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "',);", con);
object o= sc.ExecuteNonQuery();
MessageBox.Show(o +"Saved data");
con .Close();
}
I see a few things;
Patient Id should be [Patient Id] and Contact No should be [Contact No] since they are more than one word. As a best practice, change their names to one word.
You have extra , at the end of textBox5.Text + "', part.
But much more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
And use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
using(var con = new SqlConnection(connection))
using(var sc = con.CreateCommand())
{
sc.CommandText = #"insert into Patient_Details ([Patient Id],Name,Age,[Contact No],Address)
VALUES(#id, #name, #age, #no, #address)";
sc.Parameters.AddWithValue("#id", textBox1.Text);
sc.Parameters.AddWithValue("#name", textBox2.Text);
sc.Parameters.AddWithValue("#age", textBox3.Text);
sc.Parameters.AddWithValue("#no", textBox4.Text);
sc.Parameters.AddWithValue("#address", textBox5.Text);
con.Open();
int i = sc.ExecuteNonQuery();
MessageBox.Show(i + " Saved data");
}
By the way, I used AddWithValue in my example since you didn't tell us your column types but you don't. This method might generate surprising results sometimes. Use Add method overloads to specify your parameter type (SqlDbType) and it's size.
Getting an object from ExecuteNonQuery is really strange as well. It will return int as an effected rows count. It will be 1 or 0 in your case.
As a last thing, I strongly suspect your Patient Id, Age and Contact No columns should be some numeric type, not character typed.
fields and table names with spaces must be inside [], also you have 1 extra comma in the end of your query. Try:
SqlCommand sc = new SqlCommand("insert into [Patient_Details] ([Patient Id],Name,Age,[Contact No],Address) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "');", con);
object o= sc.ExecuteNonQuery();
also consider using parameters, since you are open to sql injection.
Okay so I am trying to use parameters in C# sql code block but I am getting #Data in my SQL table please help
string connectionString = #"Network Library=DBMSSOCN;Data Source=**********,1433;database=*******;User id=*****;Password=******;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//
// Description of SQL command:
// 1. It selects all cells from rows matching the name.
// 2. It uses LIKE operator because Name is a Text field.
// 3. #Name must be added as a new SqlParameter.
//
using (SqlCommand command = new SqlCommand(
"INSERT INTO [dbo].[event_logs] ([event_level],[date_and_time],[source],[event_id],[task_category],[event_data],[channel],[computer_id],[created_at],[updated_at])VALUES('" + entry.EntryType + "','" + entry.TimeWritten + "','" + entry.Source + "','" + entry.InstanceId + "','" + entry.Category + "',' #Data ','" + logtype + "','" + computerID + "','" + DateTime.Now.ToString() + "','" + DateTime.Now.ToString() + "')", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("#Data", entry.Message));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
}
}
}
INSERTs don't return results. Use .ExecuteNonQuery() instead of .ExecuteReader().
You are getting #Data because you SQL string is formatted like "',' #Data ','" which is wrong, it is no more a variable, it is itself a SQL String.
What you need to do is fix the SQL query from "',' #Data ','" to "', #Data ,'" it will be fine then.
using (SqlCommand command = new SqlCommand(
"INSERT INTO [dbo].[event_logs] ([event_level],[date_and_time],[source],[event_id],[task_category],[event_data],[channel],[computer_id],[created_at],[updated_at])VALUES('" + entry.EntryType + "','" + entry.TimeWritten + "','" + entry.Source + "','" + entry.InstanceId + "','" + entry.Category + "', #Data ,'" + logtype + "','" + computerID + "','" + DateTime.Now.ToString() + "','" + DateTime.Now.ToString() + "')", connection))
{
// Add new SqlParameter to the command.
command.Parameters.Add(new SqlParameter("#Data", entry.Message));
command.ExecuteNonQuery();
}
You need to specify the name and data type in the constructor, and the value in the new object:
command.Parameters.Add("#Data", SqlDbType.VarChar).Value = entry.Message;
private void button2_Click(object sender, EventArgs e)
{
try
{
string sSQL = "INSERT INTO StuTable (Name, Batch,CGPA, DOB, Program,
Picture)VALUES (#Name, #Batch,#CGPA,#DOB,#Program,#Picture)";
SqlCommand objCmd = new SqlCommand(sSQL, conn);
objCmd.Parameters.Add("#Name", SqlDbType.VarChar, 50);
objCmd.Parameters.Add("#Batch", SqlDbType.Int);
objCmd.Parameters.Add("#CGPA", SqlDbType.Float);
objCmd.Parameters.Add("#DOB", SqlDbType.VarChar, 50);
objCmd.Parameters.Add("#Program", SqlDbType.VarChar, 50);
objCmd.Parameters.Add("#Picture", SqlDbType.VarChar, 500);
//objCmd.Parameters["#RegdNo"].Value = Convert.ToInt32(textBox3.Text);
objCmd.Parameters["#Name"].Value = textBox4.Text;
objCmd.Parameters["#Batch"].Value = textBox5.Text;
objCmd.Parameters["#CGPA"].Value = textBox6.Text;
objCmd.Parameters["#DOB"].Value = maskedTextBox1.Text;
objCmd.Parameters["#Program"].Value = textBox8.Text;
objCmd.Parameters["#Picture"].Value = textBox9.Text;
objCmd.ExecuteNonQuery();
// MessageBox.Show("Record Added");
}
catch (Exception te)
{
MessageBox.Show(te.Message.ToString());
}
}
So I have this code to insert values from text-box into my database, but every time i execute my code and enters my data i get this message
"Syntax Error near keyword user"
string Connectionstring = #"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Bank_System.mdf;Integrated Security=True; User Instance=True";
SqlConnection cnn = new SqlConnection(Connectionstring);
cnn.Open();
SqlCommand cmd1 = new SqlCommand("insert into user values('" + int.Parse(textBox1.Text) + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + int.Parse(textBox6.Text) + "')", cnn);
SqlDataReader dr1 = cmd1.ExecuteReader();
dr1.Close();
MessageBox.Show(" Record inserted ", " information inserted");
cnn.Close();
USER is a reserved keyword in T-SQL. You should use it with square brackets like [USER]. However, the best solution is to change the name to a non-reserved word.
But more important, please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
By the way, I don't understand why you used ExecuteReader for an INSERT command. Looks like you just need to use ExecuteNonQuery instead.
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command.
Also use using statement to dispose your SqlConnection, SqlCommand.
using(SqlConnection cnn = new SqlConnection(Connectionstring))
using(SqlCommand cmd1 = cnn.CreateCommand())
{
cmd1.CommandText = "INSERT INTO [USER] VALUE(#p1, #p2, #p3, #p4, #p5, #p6)";
cmd1.Parameters.AddWithValue("#p1", int.Parse(textBox1.Text));
cmd1.Parameters.AddWithValue("#p2", textBox2.Text);
cmd1.Parameters.AddWithValue("#p3", textBox3.Text);
cmd1.Parameters.AddWithValue("#p4", textBox4.Text);
cmd1.Parameters.AddWithValue("#p5", textBox5.Text);
cmd1.Parameters.AddWithValue("#p6", int.Parse(textBox6.Text));
cnn.Open();
int count = cmd1.ExecuteNonQuery();
if(count > 0)
MessageBox.Show("Record inserted");
}
You try to concatenate int to string. The error is here: int.Parse(textBox1.Text) -> you need to convert to string after you test if is integer.
Try this for test : int.Parse(textBox1.Text).ToString() to see if this is your problem.
You try gather string to an integer by using:
"insert into user values('" + int.Parse(textBox1.Text) ....
=> string + int
Correct is:
SqlCommand cmd1 = new SqlCommand("insert into user values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "')", cnn);
try to validate if textBox1.Text and textBox6.Text before concatenate but is recommended to use parameters.