I cannot get my program to clear an SQL database on opening. I have went through debugging and there are no errors in the code for deleting, but it just doesn't do it
string delete = "Delete from Trivia";
con.Open();
SqlCommand comm = new SqlCommand(delete, con);
con.Close();
You're not actually executing the command. You might also consider a using statement. That will automatically dispose of the connection properly, even if an error occurs:
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand comm = new SqlCommand("delete from Trivia", con);
comm.ExecuteNonQuery();
}
Related
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=MYDATASOURCE";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(#IngredientID,
#AantalInVoorraad, #MinimumVoorraad";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(#IngredientID, #IngredientNaam";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
I want to insert data to the tables Voorraad and Ingredient. In the tables Voorraad there must IngredientID, AantalInVoorraad, MinimumVoorraad and Categorie be in the table after instert.
In the table Ingredient there must be an new Ingredientnaam be made. When i filling in the text boxes and after hitting the button insert i get the error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '#MinimumVoorraad'.'
Please help me!
I've edited to this:
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(#IngredientID,
#AantalInVoorraad, #MinimumVoorraad)";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(#IngredientID,
#IngredientNaam)";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
Does anybody know maybe another way to insert data to multiple tables in the datbase?? I've searched the whole internet for an answer but i can't find the right solution.
Introducing ASP.NET Web Pages - Entering Database Data by Using Forms
cmd.CommandText = "Insert into [Voorraad] (IngredientID, AantalInVoorraad, MinimumVoorraad) values(#IngredientID, #AantalInVoorraad, #MinimumVoorraad)";
and
cmd.CommandText = "insert into [Ingredient] (IngredientID, IngredientNaam) values(#IngredientID, #IngredientNaam)";
Your insert statements are missing the closing bracket for the values.
Add a using Statement for the SQlConnection and SQLCommand, will make it easier to read and debug.
using (SqlConnection con = new SqlConnection(#"Data Source=MYDATASOURCE"))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(
"Insert into [Voorraad] values(#IngredientID, #AantalInVoorraad, #MinimumVoorraad)", con))
{
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.ExecuteNonQuery();
}
using(SqlCommand cmd = new SqlCommand(
"insert into [Ingredient] values(#IngredientID, #IngredientNaam)", con))
{
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
}
}
I'm using the following code to update the data into DB.
There is no error message on console while debugging or on client screen, since parameters are correct. What could be wrong on this?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Conexion"].ConnectionString);
conn.Open();
SqlCommand actualizar = new SqlCommand();
actualizar.CommandType = CommandType.Text;
actualizar.CommandText = "update Proveedores set proveedores.nombre=#nombre,proveedores.razon_social=#razon,proveedores.rubro =#rubro,proveedores.banco=#banco,proveedores.cuenta_corriente=#cuenta_corriente where proveedores.rut_empresa=#rut";
actualizar.Parameters.AddWithValue("#rut",rut.ToString());
actualizar.Parameters.AddWithValue("#nombre",Nombre.Text);
actualizar.Parameters.AddWithValue("#razon", Razon.Text);
actualizar.Parameters.AddWithValue("#rubro",Rubro.Text);
actualizar.Parameters.AddWithValue("#banco",Banco.Text);
actualizar.Parameters.AddWithValue("#cuenta_corriente",Cuenta.Text);
actualizar.Connection = conn;
actualizar.ExecuteNonQuery();
conn.Close();
Added image on test
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO projetablosu(basvuru_no)VALUES(#basvuru_no)";
cmd.Parameters.AddWithValue("basvuru_no", textBox1.Text);
cmd.ExecuteNonQuery();
Well, if it doesn't add the record to the database you can hardly say it works, can you?
You are missing the # in the parameter. Instead of
cmd.Parameters.AddWithValue("basvuru_no", textBox1.Text);
use
cmd.Parameters.Add("#basvuru_no", SqlDbType.VarChar).Value = textBox1.Text;
You should also read Can we stop using AddWithValue() already?
Also, as Artem wrote in his comment, you should dispose your disposable objects. The proper way to do it is with the using statement:
using (var conn = new SqlConnection(#"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True"))
{
using (var cmd = new SqlCommand("INSERT INTO projetablosu(basvuru_no)VALUES(#basvuru_no)", conn))
{
cmd.Parameters.Add("#basvuru_no", SqlDbType.VarChar).Value = textBox1.Text;
cmd.ExecuteNonQuery();
}
}
Also note that you can use the constructors to pass all the properties you have set manually in your code, making the code shorter and more readable.
SqlConnection conn = new SqlConnection(#"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True");
string query = "INSERT INTO projetablosu(basvuru_no)VALUES('"+textBox1.Text+"')";
SqlCommand cmd = new SqlCommand(query,conn);
cmd.ExecuteNonQuery();
// Try This Code, This Will Definately works for u
I am building a database using Visual Studio 2008 c# and when I'm a trying to insert a new record into my database it appears that ExecuteNonQuery has not initialized. I copy my code, hope anyone can help me in this because I am new.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd.CommandText = "insert into Database1.mdf(Codigo,Nombre,Cantidad,Tipo) values('"+comboBox1.Text+"','"+textBox3.Text+"','"+textBox1.Text+"','"+comboBox2.Text+"')";
cmd.ExecuteNonQuery();
cmd.Clone();
cn.Close();
MessageBox.Show("Acabas de agregar un producto");
}
You haven't set the connection to your command:
cmd.Connection = cn;
You have numerous problems in your code:
First: The insert into statement requires a target datatable not the name of
the MDF file
Second: Employ the using statement to close and dispose the connections
Third: Parametrized query to avoid parsing problems and sql
injections
Fourth: You need to associate the connection to the command (Easily
done at the SqlCommand constructor)
using(SqlConnection cn = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand("insert into table_name(Codigo,Nombre,Cantidad,Tipo)" +
"values (#cod, #nom,#can,#tipo)", con))
{
cn.Open();
cmd.Parameters.AddWithValue("#cod", comboBox1.Text);
cmd.Parameters.AddWithValue("#nom", textBox3.Text);
cmd.Parameters.AddWithValue("#can", textBox1.Text);
cmd.Parameters.AddWithValue("#tipo", comboBox2.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Acabas de agregar un producto");
}
EDIT
The information provided by the link added by #RemusRusanu below is very important. The use of AddWithValue, whilst handy, could hinder the performance of your query. The correct approach should be the usage of a proper defined SqlParameter with both explicit datatype and parameter size.
As an example
SqlParameter p = new SqlParameter("#cod", SqlDbType.NVarChar, 255).Value = comboBox1.Text;
cmd.Parameters.Add(p);
But, of course, this requires that you check the exact datatype and size of your columns.
You did not initialize your SqlCommand with a connection. Also, you should really enclose everything here with using. And consider using parametarized commands to avoid SQL Injection.
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "insert into databaseTableName (Codigo,Nombre,Cantidad,Tipo) values (#Codigo, #Nombre, #Cantidad, #Tipo)";
cmd.Parameters.AddWithValue("#Codigo", comboBox1.Text);
cmd.Parameters.AddWithValue("#Nombre", textBox3.Text);
cmd.Parameters.AddWithValue("#Cantidad", textBox1.Text);
cmd.Parameters.AddWithValue("#Tipo", comboBox2.Text);
cmd.Connection = cn; //this was where the error originated in the first place.
cn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Acabas de agregar un producto");
}
}
}
When I try to select values from a local database it executes without any issue. But when I try to insert and delete it's executing the query but it's not affecting any rows.
This is the code I'm using to delete row from my local database:
SqlCeConnection sqlConnection1 = new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = Database1.sdf";
SqlCeCommand cmd = sqlConnection1.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "DELETE FROM table1 WHERE slno=2";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.Prepare();
int aff=cmd.ExecuteNonQuery();//here its returning '0'
MessageBox.Show(aff.ToString());
sqlConnection1.Dispose();
sqlConnection1.Close();
It is possible that the delete won't affect any rows.
As an aside, I would advise using the using statement in your code:
using (SqlCeConnection conn = new SqlCeConnection("Data Source = Database1.sdf"))
using (SqlCeCommand comm = new SqlCeCommand("DELETE FROM table1 WHERE slno = 2", conn))
{
conn.Open();
comm.CommandType = CommandType.Text;
comm.ExecuteNonQuery();
}
This will handle disposal of relevant objects for you.
Assuming that the SQL is relevant to your database and that you have successfully connected using the connection string beforehand, then the above could will perform a delete action against your database.