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();
...
}
}
Related
namespace login_page
{
public partial class itemselect : Form
{
public itemselect()
{
InitializeComponent();
}
private void product_Click(object sender, EventArgs e)
{
}
private void Addproduct_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-QI8RJIB;Initial Catalog=itemselect;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(" insert into itemselect([Product ID],[Product Name],[Product Quantity],[Product Price] values ('" +pid.Text+ "','" +pn.Text+ "','" +pq.Text+ "','" +pp.Text+ "')", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
this.Close();
MessageBox.Show("item added successfully");
}
Exception:
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword
'values'.'
Your syntax is incorrect, make sure that you have closed all your opened parenthesis.
Also, always use SqlParameters to prevent Sql injection attacks and improve code readability
Sample code
private void Addproduct_Click(object sender, EventArgs e)
{
string query = "INSERT INTO itemselect ([Product ID],[Product Name],[Product Quantity],[Product Price]) VALUES (#ProductID, #ProductName, #ProductQuantity, #ProductPrice)";
using (var con = new SqlConnection(#"Data Source=DESKTOP-QI8RJIB;Initial Catalog=itemselect;Integrated Security=True"))
using (var cmd = new SqlCommand(query, con))
{
// Not sure about ProductID type. Could be SqlDbType.UniqueIdentifier or SqlDbType.Int / BigInt
cmd.Parameters.Add(new SqlParameter("#ProductID", SqlDbType.UniqueIdentifier)).Value = pid.Text;
cmd.Parameters.Add(new SqlParameter("#ProductName", SqlDbType.NVarChar)).Value = pp.Text;
cmd.Parameters.Add(new SqlParameter("#ProductQuantity", SqlDbType.Int)).Value = pq.Text;
cmd.Parameters.Add(new SqlParameter("#ProductPrice", SqlDbType.Decimal)).Value = pp.Text;
try
{
con.Open();
cmd.ExecuteNonQuery();
// Records Inserted Successfully
}
catch (SqlException err)
{
// Error occured. Handle error
}
}
}
P.S: Please follow naming conventions when naming tables, columns and variables
You're missing a closing parathensis before the word values.
Also you should use a using statement to ensure that the connection
will be closed after the execution
You should also use a Parameters.AddWithValue() method to avoid the
SQL INJECTION
I am trying to edit an Access DB_. For some reason I cannot insert anything. I believe my code is correct. The connection string is correct (though for security purposes I put a fake one for this post). At the end, I do not get the MessageBox like I am supposed to at the end of the function. Nothing was added to the Access DB either.
Any reason why this might be?
namespace TestBuild
{
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb");
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table1 values('"+textBox1.Text+"','"+textBox2.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record inserted successfully");
}
}
}
Suggestion - please consider refactoring your code as follows, and step through it, a line at a time, in the MSVS debugger:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb";
private void Button1_Click(object sender, EventArgs e)
{
string sql = "insert into table1 values('" + textBox1.Text + "','" + textBox2.Text + "')";
OleDbCommand cmd= new OleDbCommand(sql);
using (OleDbConnection con = new OleDbConnection(connString)) {
cmd.Connection = conn;
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("record inserted successfully");
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex.Message);
}
}
}
PS:
If you wanted to use prepared statements, you'd change your code to something like this:
string sql = "insert into table1 values(#param1, #param2)";
...
cmd.Parameters.AddWithValue("#param1", textBox1.Text);
cmd.Parameters.AddWithValue("#param1", textBox2.Text);
con.Open();
cmd.Prepare();
cmd.ExecuteNonQuery();
You can read more about techniques and guidelines for mitigating SQL injection here:
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
Here is another good article:
Best Practices for Using ADO.NET (MSDN)
I have tried using methods that others have used here to fix their issue but none of them are working for me. I am new to the ASP.NET framework and cannot understand why the information I am trying to send to my database isn't working. Also, Visual Studios isn't giving em an error until I try to submit the new data which makes it difficult for me to pinpoint the problem.
namespace ylena_exercise
{
public partial class KnockoutBind : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=ylena_exercise;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
GridView1.Visible = false;
}
protected void AddBtn_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Customers ('"+numid.Text+"','"+txtcustomer.Text+"','"+txtcontact.Text+"','"+txtaddress.Text+"','"+txtcity.Text+"','"+numpostcode.Text+"','"+txtcountry.Text+"')",con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataBind();
Label1.Visible = true;
Label1.Text = "Data Stored Successfully!";
numid.Text = "";
txtcustomer.Text = "";
txtcontact.Text = "";
txtaddress.Text = "";
txtcity.Text = "";
numpostcode.Text = "";
txtcountry.Text = "";
}
}
}
Is there something wrong with my data? Or perhaps the issue is ExecuteNonQuery?
You missed Values in your insert statement your code should be like this:
SqlCommand cmd = new SqlCommand("insert into Customers values('"+numid.Text+"',....
Also you should always use parameterized queries to avoid SQL Injection:
SqlCommand cmd = new SqlCommand("insert into Customers values(#numid,...");
cmd.Parameters.AddWithValue("#numid",numid.Text);
Include column names in your sql and set the values like this:
var command = "insert into customers (id, name, contact, address, city, postcode, country) values (#id, #name, #contact, #address, #city, #postcode, #country)";
SqlCommand cmd = new SqlCommand(command);
cmd.Parameters.AddWithValue("#id", numid.Text);
cmd.Parameters.AddWithValue("#name", txtcustomer.Text);
cmd.Parameters.AddWithValue("#contact", txtcontact.Text);
cmd.Parameters.AddWithValue("#address", txtaddress.Text);
cmd.Parameters.AddWithValue("#city", txtcity.Text);
cmd.Parameters.AddWithValue("#postcode", numpostcode.Text);
cmd.Parameters.AddWithValue("#country", txtcountry.Text);
cmd.ExecuteNonQuery();
[Courtesy: Soner Gönül & user2946329]
Hey so I managed to figure out why ExecuteNonQuery was giving me issues. It turns out I simply did not match the table columns names with the variables in the SQL command.
Sorry for all of the trouble guys! Nevertheless, I appreciate all of the helpful suggestions and advice.
i'm trying to use an insert method in my studentHelperClass, I am trying to activate it on a button click on my form, I don't know how to make it work with a text box, so if someone could help with that, that would be great.
This is my method:
public static void insertStudent()
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (#personID)";
cmd.Parameters.AddWithValue("#personID", "123345667788");
prevID(conn, cmd);
}
and this is my form:
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent();
}
EDIT:
private static void prevID(MySqlConnection conn, MySqlCommand cmd)
{
conn.Open();
cmd.ExecuteNonQuery();
long studentNumber = (long)cmd.LastInsertedId;
Console.Write("previous id {0} ", studentNumber);
Console.ReadLine();
conn.Close();
}
Considering the information, assuming that your prevId(conn,cmd) is calling ExecuteNonQuery, you will still need to set the cmd.CommandText to be equal to your myInsertSql (as other answers have pointed out).
To answer your question though,
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent(studentIdTextBox.Text);
}
public static void insertStudent(string studentId)
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (?personID)";
cmd.CommandText = myInsertSQL;
cmd.Parameters.AddWithValue("?personID", studentId);
prevID(conn, cmd);
}
Ive also assumed your studentId is a string. If the database has it as a bigint, you will have to do the proper long.TryParse() call.
You need to set cmd.CommandText as myInsertSQL
and also need to call cmd.ExecuteNonQuery()
string sql = "INSERT INTO person (personID) VALUES (#personID)";
using (MySqlConnection conn = connection())
using (MySqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#personID", personID);
conn.Open();
cmd.ExecuteNonQuery();
}
You must assign your string variable, 'myInsertSQL' to cmd.CommandText, and then call, cmd.ExecuteNonQuery();
I.e.
cmd.CommandText = myInsertSQL;
cmd.ExecuteNonQuery();
cmd.Dispose();
Always call 'Dispose();' when finished so the .net Garbage Collection can cleanup and manage resources.
You don't use the myInsertSQL string at all, you just set it. You have to set the string as the command text by cmd.CommandText = myInsertSQL and you have to call the method cmd.ExecuteNonQuery().
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 = ?