I'm Having some trouble deleting an entry on my database.
I can insert data, but i can't delete them.
I have a 2 variables database, and i want to manage those data.
but when i debug the program , the first button (btnAdicionar) works fine, but when i press the button "btnRemover", i get an erron on the line "cmd.ExecuteNonQuery();"
what am i doing wrong? thanks
here is the code:
private void btnAdicionar_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\BancodeDados\\Nomes.mdb");
string sql = "INSERT INTO Nomes (Nome, Sobrenome) VALUES(?, ?)";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
cmd.Parameters.AddWithValue("Nome", txtNome.Text);
cmd.Parameters.AddWithValue("Sobrenome", txtSobre.Text);
cmd.ExecuteNonQuery();
conn.Close();
this.nomesTableAdapter.Fill(this.nomesDataSet.Nomes);
}
private void btnRemover_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\BancodeDados\\Nomes.mdb");
string sql = "DELETE FROM Nomes (Nome, Sobrenome) WHERE (?, ?)";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
cmd.Parameters.AddWithValue("Nome", txtNome.Text);
cmd.Parameters.AddWithValue("Sobrenome", txtSobre.Text);
cmd.ExecuteNonQuery();
conn.Close();
this.nomesTableAdapter.Fill(this.nomesDataSet.Nomes);
}
Your delete statement is not valid SQL, hence the error when you call ExecuteNonQuery
It should be something like this:
DELETE FROM Nomes WHERE Nome= ? and Sobrenome = ?
Related
I have the following code:
SqlCommand writeCommand = new SqlCommand("INSERT INTO computers(id)VALUES()", conn.GetConnection());
writeCommand.ExecuteNonQuery();
The table computers contains an INT idientity(1,1) column named id.
When I run the code, I get a System.Data.SqlClient.SqlException: Incorrect syntax near ')'. I've tried to find a solution, but can't find one on the internet.
If the table has other columns as well, and you want to populate them with NULL or their DEFAULT values, then you can use DEFAULT VALUES:
INSERT INTO dbo.computers
DEFAULT VALUES;
If, however, your table only have the one column, then personally using an IDENTITY is the wrong choice; a table that just has an IDENTITY is clearly being misused. Instead, use a SEQUENCE:
CREATE SEQUENCE dbo.Computers START WITH 1 INCREMENT BY 1;
This scales far better, and doesn't suffer the likely race conditions you have. Then, when running an INSERT (or similar) you would use NEXT VALUE FOR dbo.Computers.
For an auto-incrementing identity column the database handles the id value unless I missed something in what you are attempting to do.
public void DemoInsert(string ComputerName, ref int newIdentifier)
{
using (var conn = new SqlConnection { ConnectionString = ConnectionString })
{
using (var cmd = new SqlCommand { Connection = conn })
{
cmd.CommandText = "INSERT INTO computers (ComputerName) " +
"VALUES (#ComputerName); " +
"SELECT CAST(scope_identity() AS int);";
cmd.Parameters.AddWithValue("#ComputerName", ComputerName);
cn.Open();
newIdentifier = (int)cmd.ExecuteScalar();
}
}
}
I have similar code like your app, think about it simple crud app
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con;
SqlDataAdapter da;
SqlCommand cmd;
DataSet ds;
void fillGrid()
{
con = new SqlConnection("Data Source=.;Initial Catalog=schoolDb;Integrated Security=True");
da = new SqlDataAdapter("Select * from ogrenciler",con);
ds = new DataSet();
con.Open();
da.Fill(ds, "students");
dataGridView1.DataSource = ds.Tables["students"];
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
fillGrid();
}
private void Addbtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText="insert into students(StudentId,StudentName,StudentSurname,City) values("+StudentId.Text+",'"+StudentName.Text+"','"+StudentSurname.Text+"','"+City.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Updatebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "update Students set ogrenci_ad='"+StudentName.Text+"',StudentName='"+StudentSurname.Text+"',City='"+City.Text+"' where StudentId="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Deletebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "delete from ogrenciler where ogrenci_no="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
}
}
This is the code I'm working with right now, I don't get any errors so I can't pinpoint where it's not working:
private void btnAdd_Click(object sender, EventArgs e)
{
string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
string query =
"INSERT INTO Products (Barcodes, Name, EDate, Quantity, Price) VALUES (#barcodeValue, #nameValue, #dateValue, #quantityValue, #priceValue) ;";
SqlConnection conDataBase = new SqlConnection(constring);
conDataBase.Open();
using (var cmd = new SqlCommand(query, conDataBase))
{
cmd.Parameters.AddWithValue("#barcodeValue", tbxBar.Text);
cmd.Parameters.AddWithValue("#nameValue", tbxName.Text);
cmd.Parameters.AddWithValue("#dateValue", dateDate.Value.Date);
cmd.Parameters.AddWithValue("#quantityeValue", tbxQua.Text);
cmd.Parameters.AddWithValue("#priceValue", tbxPrice.Text);
}
conDataBase.Close();
}
The code might just be wrongly build or I could be missing some part I'm not sure.
I figured out what was not working, was the connection string. So opening a new question for that.
What i had to do is to open the connection and then execute the command
You're not actually running the command. You need to call ExecuteNonQuery or ExecuteScalar:
using (var cmd = new SqlCommand(query, conDataBase))
{
// set parameters...
cmd.ExecuteNonQuery();
}
I have a very basic and beginner problem. I got a 5 line code and I got exception in that.
My database :
It has one table and two columns inside the table viz. id and name.
I made a form.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn);
command.ExecuteNonQuery();
conn.Close();
}
I get the following exception on running the code:
It says that I have syntax error even though the syntax error is correct. Any help would be appreciated.
Thankyou!
You should use a using clause to properly manage resources and use parameters to avoid security problems. It is not recommended to use reserved words as "table". Try this:
const string commandText = "INSERT INTO [Table] (id,name) VALUES (1,#Name)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = textBox1.Text;
connection.Open();
var rowsAffected = command.ExecuteNonQuery();
}
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dimmer\Documents\Visual Studio 2013\Projects\Manage components\Manage components\Database1.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
loadlist();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "")
{
cn.Open();
cmd.CommandText = "insert into info (id,name) values ('"+txtid.Text+"'.'"+txtname.Text+"')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record instered!");
txtid.Text = "";
txtname.Text = "";
loadlist();
}
}
}
I am new to C# and I have been trying for some hours with a insert code to a service-based database. I have tested the connection to it and it works.
I got this error message:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'xxxx'.
Where xxxx is what I insert into my 2nd textbox. The code stops at
cmd.ExcecuteNonQuery();
I have been searching for an answers for hours, I believe there is something wrong with the database.
Sorry if this code looks ugly, but I had some problems with spaces :P
You didn't tell us what are txtid.Text and txtname.Text exactly but..
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
cmd.CommandText = "insert into info (id,name) values (#id, #name)";
cmd.Parameters.AddWithValue("#id", txtid.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.ExecuteNonQuery();
Looks like you're reusing a connection and you probably have not closed it last time.
You should always close a connection immediately as soon as you're finished with it. Use using statement like;
using(var cn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(query, cn))
{
if (txtid.Text != "" & txtname.Text != "")
{
cmd.CommandText = "insert into info (id,name) values (#id, #name)";
cmd.Parameters.AddWithValue("#id", txtid.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
...
}
}
I am working In c# and inserting my data into an Access database. It runs properly but crashes when I try to insert data, any idea why?
public partial class StudentInfo : Form
{
private OleDbConnection myCon;
public StudentInfo()
{
InitializeComponent();
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\database program\database program\Students.mdb");
}
private void InsertBtn_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Insert into StudentInfo(Rollno,SName,SFather,SAdress) Values ('"+ Rollnotb.Text+"','"+nametb.Text+"','"+fathertb.Text+"','"+adresstb.Text+"')";
cmd.Connection=myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
}
The problem can be that you are inserting all fields as text values and maybe some are defined as numeric in the MS Access table (rollNo?)
Also, get used to using paremeters in your queries:
cmd.CommandText = "Insert into StudentInfo(Rollno,SName,SFather,SAdress) Values (?,?,?,?)";
cmd.Parameters.Add(new OleDbParameter("#rollNo", rollNoValue)); //etc.