我的数据没有保存在我的数据库中 - C#visual studio

时间:2015-07-01 13:49:47

标签: c# sql-server

我有这个问题,视觉工作室没有显示任何类型的错误,但当我尝试保存数据并且我去检查我的数据库时,它是空的,不知道错误在哪里,请帮助

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();

                }
            }
        }

1 个答案:

答案 0 :(得分:7)

显然,你从不执行你的命令。

使用ExecuteNonQuery执行它。你的Clone似乎没必要,因为你没有保留复制的命令。

但更重要的是,您应该始终使用parameterized queries。这种字符串连接对SQL Injection攻击开放。

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();
}

我在我的示例中使用了AddWithValue方法,因为我不知道您的列类型,但您不使用此方法。有时It may generate unexpected and surprising results。使用Add overloads指定参数类型及其大小。