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();
Related
private void btnsave_Click(object sender, EventArgs e)
{
string dbpath = #"Data Source=ABC;Initial Catalog=ApplicationForm;Integrated Security=True";
SqlConnection con = new SqlConnection(dbpath);
con.Open();
string savequerybscs="insert into bscs values('"+txtapplicantnumber.Text+"','"+txtname.Text+"','"+txtfathername.Text+"','"+txtmatrictotal.Text+"','"+txtmatricobtained.Text+"','"+txtmatricpercent.Text+"','"+txtintertotal.Text+"','"+txtinterobtained.Text+ "','"+txtinterpercent.Text+"')";
string savequerybsit ="insert into bsit values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "')";
string savequerymcs ="insert into bscs values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "','"+txtbachelortotal.Text+"','"+txtbachelorobtained.Text+"','"+txtbachelorpercent.Text+"')";
string savequerymit ="insert into bscs values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "','" + txtbachelortotal.Text + "','" + txtbachelorobtained.Text + "','" + txtbachelorpercent.Text + "')";
SqlCommand cmd = new SqlCommand(savequerybscs,savequerymcs,bla blaa);
}
As you can see, this solution is pretty messed up. Is there any other way to handle such issues? All I want is to insert data in multiple tables simultaneously but SqlCommand only takes 1 argument.
I just learned about bulk query or bulk insertion. Can someone guide me through that? I am not clearly getting those concepts from youtube.
You can do one insert query using the comma separator between tuples for multiples rows:
insert into bsit values (field1, field2...), (field1, field2...), ...
But this insert is for one table.
Basically, you use as many SQL query as many table you want to update.
I'm not advanced but perhaps, depending on the database server, you could execute a "script" in one C# SqlCommand execute non query call, using the semilicon separator, like:
string sql = "insert into table1 values (field1, field2...), (field1, field2...), ... ; "
+ "insert into table2 values (field1, field2...), (field1, field2...), ... ;";
MySql should support that.
You should use SQL Parameters for security reason instead of adding values to the sql string itself:
string sql = "insert into table1 values (?, ?)";
var command = new OdbcCommand(sql, connection);
command.Parameters.Add("#ID", OdbcType.Text).Value = Guid.NewGuid().ToString();
command.Parameters.Add("#Name", OdbcType.Text).Value = "Test";
command.ExecuteNonQuery();
https://learn.microsoft.com/dotnet/api/system.data.sqlclient.sqlcommand.parameters
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 was watching https://www.youtube.com/watch?v=SJ-RyDl5E7U It basically teaches me how to create my update and delete button after following the video my program works just like his!
But there is no "checking" statement for my btnSave, allowing the user to enter duplicated data in the data base if they click more than once shown here
So I was wondering if there is a "checking statement" I can use, like if the IndexNumber (first column) exist there will be a message box showing out saying something like "ID is already exists"
This is my current code for the btnSave
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text + "','" + numGPA.Value + "')", con);
cmd.ExecuteNonQuery();
con.Close();
As you are using ado.net something like this;
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + "Application.StartupPath" + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
//get a count records with your index number
SqlCommand validate = new SqlCommand(string.Format("SELECT count(IndexNumber) FROM GlennTeoStudents WHERE IndexNumber = {0}", numIN.Value), con);
int count = (Int32)validate.ExecuteScalar();
if (count == 0)
{
//insert your unqiue index number into a new row
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text + "','" + numGPA.Value + "')", con);
cmd.ExecuteNonQuery();
}
else
{
//don't insert it, do something else like return an error
}
con.Close();
You should add an existence check:
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value +
"','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text +
"','" + numGPA.Value + "') WHERE NOT EXISTS ( SELECT * FROM
GlennTeoStudents WHERE IndexNumber = '" + numIN.Value + "')", con);
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);
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.