Insert query is not working properly in c# window - c#

I am creating a window application and I've chosen a database from the New Item menu. My insert query below is not executing:
con.Open();
cmd = new SqlCommand("insert into record values('" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + textBox9.Text + "','" + textBox10.Text + "','" + textBox11.Text + "','"+textBox13.Text+"','"+textBox12.Text+"')", con);
cmd.ExecuteNonQuery();
con.Close();

In Sql when your Insert query does not contain the column names then the values have to be in the correct order. Maybe this is why it is failing. You did not provide us with an error so i dont know.
You are trying this:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
I am suggesting to try this:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);

If you can you should use parameters and include your column names (like how Andreas suggested) . An example would be...
cmd = new SqlCommand("INSERT INTO record (column1, column2, column3,...)
VALUES (#data1, #data2, #data3,...)", con);
cmd.Parameters.AddWithValue("#data1", textbox2.Text);
cmd.Parameters.AddWithValue("#data2", textbox3.Text);
cmd.Parameters.AddWithValue("#data3", textbox4.Text);
cmd.Parameters.AddWithValue("...", ...);
con.Open();
cmd.ExecuteNonQuery();
con.Close();

Related

Trouble inserting number with commas into database

I have a problem of inserting numbers with comma into database. It only accepts dot but i have function that only works with commas so is there any idea to solve this like converting decimal seperation from dot to comma
if (radioButton1.Checked)
{
Avance = 200;
}
else if (radioButton2.Checked)
{
Avance = 0;
}
cnx.Open();
SqlCommand cmd = cnx.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Employeur values('" + this.txt_ID.Text + "','" + this.txt_Nom.Text + "','" + this.txt_QUA.Text + "','" + this.txt_Salaire.Text + "','" + this.txt_NBRJ.Text + "','" + this.txt_HSUP.Text + "','" + this.txt_SalireHeur.Text + "','" + this.txt_Somme.Text + "','" + this.txt_Dette.Text + "','" + this.Avance + "','" + this.txt_Credit.Text + "','" + this.txt_Montant.Text + "','" + this.txt_Paye.Text + "','" + this.txt_Reste.Text + "')";
cmd.ExecuteNonQuery();
cnx.Close();
MessageBox.Show("Se payement est enregistrer");
You desperately need to learn how to parameterize your queries. You have several other issues going on here to. Here is a shortened version of how this query should look. Of course I would prefer to get the query out of my code entirely with a stored procedure.
cmd.CommandText = "insert into Employeur (ID, Nom) values(#txt_ID, #txt_Nom)";
cmd.Parameters.Add("#txt_ID", SqlDbType.VarChar, 30).Value = this.txt_ID.Text;
cmd.Parameters.Add("#txt_Nom", SqlDbType.VarChar, 30).value = this.txt_Nom.Text;
You would need to set the appropriate datatypes and sizes to your tables.
Also, look into the USING statement. And never just reuse a connection.
To expand on Sean's comment, the least you want is something like this:
cnx.Open();
using(SqlCommand cmd = cnx.CreateCommand()) {
cmd.CommandType = CommandType.Text;
// I've cut this down a bit to save my typing fingers - you need all your cols and values
cmd.CommandText = "insert into Employeur (Salaire) values(#Salaire)";
cmd.Parameters.Add(new SqlParameter("#Salaire", decimal.Parse(txtSalaire.Text));
cmd.ExecuteNonQuery();
}
cnx.Close();
You should also have a using around you cnx creation, but you haven't shown it above.

Error in insert query in visual studio

I'm new in this field. Trying to insert the values from textbox to my database table, but I get an error at
adapter.InsertCommand.ExecuteNonQuery();
Can anyone help me solve this?
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql,con);
adapter.InsertCommand = new SqlCommand(sql,con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();
Since your table is called table and that is a SQL reserved word, you have two choices:
Change your table name. This is the only option you should be considering but for completeness;
Quote the name of the table:
insert into [table] values....
You do not list your column name on insert. This means you are also attempting to insert your identity column as well. Always list your column names
insert into NewName (firstname, lastname, username, email, password, contact)
values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')
Yes I've done it .I was using "user" in table column which is not allowed .After changing the column name everything works.
This is the code
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql, con);
adapter.InsertCommand = new SqlCommand(sql, con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();

Insert item to database

I have a problem with insert into statement..
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#Position", comboBox1.SelectedValue);
con.Open();
int n = cmd.ExecuteNonQuery();
//cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Inserted");
loaddata();
rno++;
}
else
MessageBox.Show("No Insert");
ERROR : Syntax Error INSERT INTO
Anyone can advise me? Please, Sorry for my bad English grammar.
Seem like you are missing out a parameter in your query, try using this
cmd.CommandText = "insert into Table1 (id,Position) values (#id,#Position)";
cmd.parameters.addwithvalue("#id", textBox1.Text);
cmd.parameters.addwithvalue("#Position", combobox1.selectedvalue);
new updated
-the position is the oleh db reserved words, try change to this query, put the cover to Position like below
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,[Position],Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
You have missed adding #Photo parameter in your code.
That is ok for testing purpose but you should never insert to database this way. This expose your system to a SQL Injection. You should use parametrized queries where possible. Something like
int result=0;
using (OleDbConnection myConnection = new OleDbConnection ("YourConnectionString"))
{
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) values (#ID, #Gender, #DateOfBirth, #Race, #WorkingPlace, #PassportNO, #DateOfExpire, #Position, #Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#ID", textBox5.Text);
// Specify all parameters like this
try
{
con.Open();
result = Convert.ToInt32(cmd.ExecuteNonQuery());
}
catch( OledbException ex)
{
// Log error
}
finally
{
if (con!=null) con.Close();
}
}
if(result > 0)
// Show success message
Also note that OleDb parameters are positional, means you have to
specify them in the exact order as in your query. OleDbParameter Class (MSDN)
There is no value for parameter #Photo, and if your photo field is not nullable or empty
in database structure then how you can add null value in that.So make your data field
nullable or pass value to parameter #Photo.I think it will solve your problem.
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#Position", comboBox1.SelectedValue);
cmd.Parameters.AddWithValue("#Photo", assignvalue);
con.Open();
int n = cmd.ExecuteNonQuery();
//cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Inserted");
loaddata();
rno++;
}
else
MessageBox.Show("No Insert");

Insert statement won't insert Null value

I'm trying to insert a null value into my database from C# like this:
SqlCommand command = new SqlCommand("INSERT INTO Employee
VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text
+ "','" + phone.Text + "','" + DBNull.Value + "')", connection);
DBNull.Value is where a date can be but I would like it to be equal to null but it seems to put in a default date, 1900 something...
Change to:
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text + "','" + phone.Text + "',null)", connection);
DBNull.Value.ToString() returns empty string, but you want null instead.
However this way of building your query can lead to issues. For example if one of your strings contain a quote ' the resulting query will throw error. A better way is to use parameters and set on the SqlCommand object:
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES (#empId,#name,#age,#phone,null)", connection);
command.Parameters.Add(new SqlParameter("#empId", employeeId.Text));
command.Parameters.Add(new SqlParameter("#name", name.Text));
command.Parameters.Add(new SqlParameter("#age", age.Text));
command.Parameters.Add(new SqlParameter("#phone", phone.Text));
Use Parameters.
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES
(#employeeID,#name,#age,#phone,#bdate)",connection);
....
command.Parameters.AddWithValue("#bdate",DBNull.Value);
//or
command.Parameters.Add("#bdate",System.Data.SqlDbType.DateTime).Value=DBNull.Value;
Or try this,
SqlCommand command = new SqlCommand("INSERT INTO Employee
(employeeID,name,age,phone) VALUES
(#employeeID,#name,#age,#phone)",connection);
Change DBNull.Value to the literal null for dynamic SQL:
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text + "','" + phone.Text + "',null)", connection);
Try this:
SqlCommand command = new SqlCommand();
command.ComandText = "insert into employee values(#employeeId, #name, #age, #phone, #someNullVal)";
command.Parameters.AddWithValue("#employeedId", employeedID.Text);
// all your other parameters
command.Parameters.AddWithValue("#someNullVal", DBNull.Value);
This solves two problems. You explicit problem (with inserting a NULL value into the table), and SQL Injection potential.
if you output "'" + DBNull.Value + "'" , you will find that it's '' , which means you insert an empty string instead of null into the DB. So, you just write null:
SqlCommand command = new SqlCommand("INSERT INTO Employee
VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text
+ "','" + phone.Text + "', null)", connection);
try it like this.
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text +
"','" + name.Text + "','" + age.Text + "','" + phone.Text + "','Null')", connection);

How to insert a record with a primary key in ms access database c#

I am using the following command for inserting a record in an MS Access database:
OleDbCommand cmd = new OleDbCommand("insert into Table1 values('" + Name + "','" +
Symbol + "','" + D + "','" + Red + "','" + RedBuy + "','" + RedSell + "','" +
SBIntraBuy + "','" + SBTR1Buy + "','" + SBTR2Buy + "','" + SBTR3Buy + "','" +
SBIntraSell + "','" + SBTR1Sell + "','" + SBTR2Sell + "','" + SBTR3Sell + "','" + RSTL
+ "','" + Green + "');", con);
I want to add a column before Name called CustomerId with a Primary key. I don't know how to insert it with primary key. What i should add in my command for primary key?
There would be a great appreciation if someone could help me.
Thanks In Advance.
Check this link for screen shot of the table layout.
If your key is auto increment, then you don't need to. The database will do it for you. If your key is not auto increment, consider changing it. It's really neat!
Also, please consider using binding instead of building a full insert query.
Suppose the following table:
Table1
PK (auto_increment)
Name
Symbol
What you will want to do is:
OleDbCommand cmd = new OleDbCommand("insert into Table1 (Name,Symbol) values (?,?)");
cmd.Parameters.Add(new OleDbParameter("#Name",Name));
cmd.Parameters.Add(new OleDbParameter("#Symbol",Symbol));
or (safer):
OleDbCommand cmd = new OleDbCommand("insert into Table1 (Name,Symbol) values (#Name,#Symbol)");
cmd.Parameters.Add(new OleDbParameter("#Name",Name));
cmd.Parameters.Add(new OleDbParameter("#Symbol",Symbol));
And finally:
cmd.ExecuteNonQuery();

Categories