Reputation: 25
I have this problem, visual studio don't show any kind of error, but when i try to save the data and i go check my data base, it's empty, don't know where the error is, little help please
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.IO;
using System.Runtime.InteropServices;
namespace PAPA
{
public partial class Form11 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\Documents\basededadospap.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd = new SqlCommand();
public Form11()
{
InitializeComponent();
}
void Fillcombo() {
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" & textBox2.Text != "" & textBox3.Text != "" & textBox4.Text != "" & textBox5.Text != "")
{
using (var connection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\Documents\basededadospap.mdf;Integrated Security=True;Connect Timeout=30"))
{
connection.Open();
var cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO fornecedor (nomefornecedor,nmrcontribuinte,morada,email,obs) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "' , '" + textBox5.Text + "')";
cmd.Clone();
MessageBox.Show(" Fornecedor inserido com sucesso! ");
cn.Close();
}
}
}
Upvotes: 1
Views: 1644
Reputation: 98868
Obviously, you never execute your command.
Use ExecuteNonQuery
to execute it. And your Clone
seems unnecessary since you don't keep the copied command of that.
But much more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
string conString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\Documents\basededadospap.mdf;Integrated Security=True;Connect Timeout=30");
using(var connection = new SqlConnection(conString))
using(var cmd = connection.CreateCommand())
{
cmd.CommandText = @"INSERT INTO fornecedor (nomefornecedor,nmrcontribuinte,morada,email,obs)
VALUES (@nome, @nmr, @mora, @email, @obs)";
cmd.Parameters.AddWithValue("@nome", textBox1.Text);
cmd.Parameters.AddWithValue("@nmr", textBox2.Text);
cmd.Parameters.AddWithValue("@mora", textBox3.Text);
cmd.Parameters.AddWithValue("@email", textBox4.Text);
cmd.Parameters.AddWithValue("@obs", textBox5.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
I used AddWithValue
method in my example since I didn't know your column types but you don't use this method. It may generate unexpected and surprising results sometimes. Use Add
overloads to specify your parameter type and it's size.
Upvotes: 7