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.
Related
I have a little problem with an error. but I have this command in another form and do not give me the error.
This is the code:
string select = "select CONCAT(nume,' ',prenume) from echipa where email=#EMAIL";
cmd.Connection = con;
if (bunifuCheckbox1.Checked == true)
{
con.Open();
cmd.CommandText = "Insert into clienti_fizici(nume,prenume,email,telefon,adresa,data_nasterii,data_ora,CNP,sex,judetprovenienta,temperamentclient,provenientaclient,descriere,numeagent)values('"
+ bunifuMaterialTextbox1.Text + "','" + bunifuMaterialTextbox2.Text + "','" + bunifuMaterialTextbox4.Text + "','" + bunifuMaterialTextbox8.Text + "','" + bunifuMaterialTextbox3.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd HH: mm:ss") + "','" + bunifuDatepicker1.Value.Date + "','" + bunifuMaterialTextbox11.Text + "','" + gender + "','" + bunifuMaterialTextbox12.Text + "','" + bunifuDropdown1.selectedValue + "','" + bunifuDropdown2.selectedValue
+ "','" + richTextBox1.Text + "','" + select + "')";
cmd.Parameters.AddWithValue("#EMAIL", loginform.Email);
MessageBox.Show("Datele au fost introduse in baza de date !");
cmd.ExecuteNonQuery();
con.Close();
}
and the error would be from that select.
First, you must never concatenate strings with user input to create SQL Statement. Instead, always parameterize your SQL statements. Otherwise you are risking SQL injection attacks.
Second, you can't use select inside the values clause.
What you can do add parameters or hard coded values to your select statement.
Third, SqlConnection and SqlCommand both implement the IDisposable interface and should be used as a local variable inside a using block.
A better code would look like this:
if (bunifuCheckbox1.Checked == true)
{
string sql = "Insert into clienti_fizici(nume, prenume, email, telefon, adresa, data_nasterii, data_ora, CNP, sex, judetprovenienta, temperamentclient, provenientaclient, descriere, numeagent) " +
"SELECT #nume, #prenume, #email, #telefon, #adresa, #data_nasterii, #data_ora, #CNP, #sex, #judetprovenienta, #temperamentclient, #provenientaclient, #descriere, CONCAT(nume,' ',prenume) " +
"FROM echipa where email = #EMAIL";
// Note: SqlConnection should be opened for the shortest time possible - the using statement close and dispose it when done.
using(var con = new SqlConnection(connectionString))
{
// SqlCommand is also an IDisposable and should be disposed when done.
using(var cmd = new SqlCommand(sql, con)
{
cmd.Parameters.Add("#nume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox1.Text;
cmd.Parameters.Add("#prenume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox2.Text;
//... Add the rest of the parameters here...
cmd.Parameters.Add("#EMAIL", SqlDbType.NVarChar).Value = loginform.Email;
// Why is this here? MessageBox.Show("Datele au fost introduse in baza de date !");
con.Open();
cmd.ExecuteNonQuery();
}
}
}
Here's my code:
con.Open();
String query = "INSERT INTO tbl_score (personality,style,poise,audience,total) VALUES ('" +
textBox1.Text + "','" + textBox2.Text + "','" +textBox3.Text + "','" +
textBox4.Text + "','" + textBox5.Text + "',)";
MySqlDataAdapter SDA = new MySqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show("Succesfully Voted");
I get this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near ')' at line 1
You should ALWAYS (no exceptions!) use parameters for your queries - it first of all avoids the #1 threat on the internet - SQL injection - and it also avoids messy issues with quotes around strings and so forth.
Try this code:
string query = "INSERT INTO tbl_score (personality, style, poise, audience, total) " +
"VALUES (#personality, #style, #poise, #audience, #total);";
using (MySqlCommand cmd = new MySqlCommand(query, con))
{
// set the parameter values
cmd.Parameters.Add("#personality", MySqlDbType.VarChar, 100).Value = textBox1.Text;
cmd.Parameters.Add("#style", MySqlDbType.VarChar, 100).Value = textBox2.Text;
cmd.Parameters.Add("#poise", MySqlDbType.VarChar, 100).Value = textBox3.Text;
cmd.Parameters.Add("#audience", MySqlDbType.VarChar, 100).Value = textBox4.Text;
cmd.Parameters.Add("#total", MySqlDbType.VarChar, 100).Value = textBox5.Text;
// open connection, execute INSERT query, close connection
con.Open();
int rowsInserted = cmd.ExecuteNonQuery();
con.Close();
}
MessageBox.Show("Succesfully Voted");
Also, you should use the most appropriate datatype for your parameters - if a values is numerical (as I suspect for #total), then you should use a numeric datatype - don't just cast everything to a string - use the correct datatypes.
You need to remove comma(,) before end brace.
Your query must be
String query = "INSERT INTO tbl_score (personality,style,poise,audience,total) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";
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();
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");
1.
$con = mysql_connect("localhost","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jbell2", $con);
$sql="INSERT INTO Profile (username, Date, Height, Weight, WaistSize, WeightforHeight, Blood_Pressure, Medication, Total_Cholesterol, Bad_Cholesterol, Good_Cholesterol, Triglycerides,KidneyFunctionTest)
VALUES
('$_Post[username]', '$_POST[Date]', '$_POST[Height]', '$_POST[Weight]', '$_POST[WaistSize]','$_POST[WeightforHeight]', '$_POST[Blood_Pressure]','$_POST[Medication]' ,'$_POST[Total_Cholesterol]' ,'$_POST[Bad_Cholesterol]' ,'$_POST[Good_Cholesterol]','$_POST[Triglycerides]','$_POST[KidneyFunctionTest]' )";
2
.
MySqlConnection con = new MySqlConnection("host="";user="";password=""; database="";");
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO Patients(username, password, FirstName, SecondName, DiabetesType, Email,Phone, Phone2, Question1, Question2,TreatmentPlan)"
+ "values" + "('" + uname.Text + "','" + password.Text + "','" + fname.Text + "','" + lname.Text + "','" + Dtype.Text + "','" + email.Text + "','" + phone.Text + "','" + phone2.Text + "','" + q1.Text + "','" + q2.Text + "','" + treatment.Text + "')");
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
In the C# portion:
MySqlCommand cmd = new MySqlCommand("INSERT INTO Patients (username, password, FirstName,
//...
+ "values" + "('" + uname.Text + "','" + password.Text + "','" + fname.Text + "','" +
//...
+ "')");
These values should be passed in as parameters. Your command text should be built like this:
MySqlCommand cmd = new MySqlCommand("INSERT INTO Patients (username, password, FirstName,
//...
+ "values (#username, #password, #FirstName,
//...
+ "')");
Under that, you should have something like this:
cmd.Parameters.AddWithValue("username", uname.Text);
cmd.Parameters.AddWithValue("password", password.Text);
cmd.Parameters.AddWithValue("FirstName", fname.Text);
//...
If you don't, you're asking for a lot of trouble.
Dunno about PHP but in C# you can use Parameters instead of directly injecting the values.
using (MySqlConnection con = new MySqlConnection("host="";user="";password=""; database="";"))
{
con.Open();
string strSQL = "INSERT INTO Patients(username, password, FirstName, SecondName, DiabetesType, Email,Phone, Phone2, Question1, Question2,TreatmentPlan) values (?name, ?password, .....)";
using (MySqlCommand cmd = new MySqlCommand(strSQL, con))
{
cmd.Parametrs.AddWithValue("?name", fname.Text);
cmd.Parametrs.AddWithValue("?password", lname.Text);
..........
cmd.ExecuteNonQuery();
}
}
Just have ? followed by some identifier to mark that you add parameter, then use AddWithValue to insert the real value.
Also showing how to use using which dispose of the objects properly.
In first you don't have any word in SQL language.
In 2 and 3 you are creating SQL Query by concating string, this is wrong; in 2 you can use PDO to prepare PDOStatement object and execute it passing arguments securely, in second you can probably prepare this query and pass arguments but must read documentation how do this.
Read this: http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
for option 2. you should definately be real escaping your strings at minimum before inserting in to DB with mysql_real_escape_string().
and you should always validate your data before inserting in to db. check you are getting the data you want, and replace any chars you should be getting.