C# - 插入SQL Server而不进行更改

时间:2017-12-03 22:14:42

标签: c# sql-server

C#的新手。

我正在尝试使用Windows窗体执行简单的INSERT SQL语句。  应该发生什么是当按下按钮时它将执行一个SQL语句但是当我按下它时没有任何反应。

我有什么遗失的吗?

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.SqlClient;

namespace windowFormsApp_test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'por_testDataSet.tbl_persons' table. You can move, or remove it, as needed.
            this.tbl_personsTableAdapter.Fill(this.por_testDataSet.tbl_persons);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connectionString = "Data Source=DC-POR\\SQLEXPRESS;Initial Catalog=por_test;Integrated Security=True;";

            SqlConnection con = new SqlConnection(connectionString);

            con.Open();

            string sql = "INSERT into tbl_persons (person_id,p_name,p_surname) VALUES (55,'TEST','test')";
            SqlCommand cmd = new SqlCommand(sql);

            con.Close();
        }

1 个答案:

答案 0 :(得分:2)

您需要致电ExecuteNonQuery来实际插入。

代码应如下:

private void button1_Click(object sender, EventArgs e)
{
        string connectionString = "Data Source=DC-POR\\SQLEXPRESS;Initial Catalog=por_test;Integrated Security=True;";

        SqlConnection con = new SqlConnection(connectionString);
        con.Open();

        string sql = "INSERT into tbl_persons (person_id,p_name,p_surname) VALUES (55,'TEST','test')";
        SqlCommand cmd = new SqlCommand(sql);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();

        con.Close();
    }

您不应将值直接传递给insert语句。相反,您应该使用parameters.add来传递值。因此,执行SQL的更好方法是

private void button1_Click(object sender, EventArgs e)
{
    string connectionString = "Data Source=DC-POR\\SQLEXPRESS;Initial Catalog=por_test;Integrated Security=True;";

    using(SqlConnection con = new SqlConnection(connectionString))
    {             
        string sql = @"INSERT into tbl_persons (person_id, p_name, p_surname) VALUES (@param1, @param2, @param3)";

       using(var cmd = new SqlCommand())
       {
           cmd.Connection = conn;
           cmd.CommandType = CommandType.Text;
           cmd.CommandText = sql;

           cmd.Parameters.AddWithValue("@param1", 55);  
           cmd.Parameters.AddWithValue("@param2", 'TEST');  
           cmd.Parameters.AddWithValue("@param3", 'test1');

           con.Open();
           cmd.ExecuteNonQuery();
        }
    }
}