【问题标题】:SQL Insert Query Using C#使用 C# 的 SQL 插入查询
【发布时间】:2013-11-26 05:12:06
【问题描述】:

我目前遇到了一个我正在尝试解决的问题。我只是尝试在 C# 的帮助下访问数据库并插入一些值

我尝试(工作)的事情

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc',      'abc', 'abc', 'abc')";

插入了新行,一切正常,现在我尝试使用变量插入一行:

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id, @username, @password, @email)";

command.Parameters.AddWithValue("@id","abc")
command.Parameters.AddWithValue("@username","abc")
command.Parameters.AddWithValue("@password","abc")
command.Parameters.AddWithValue("@email","abc")

command.ExecuteNonQuery();

不起作用,没有插入任何值。我又尝试了一件事

command.Parameters.AddWithValue("@id", SqlDbType.NChar);
command.Parameters["@id"].Value = "abc";

command.Parameters.AddWithValue("@username", SqlDbType.NChar);
command.Parameters["@username"].Value = "abc";

command.Parameters.AddWithValue("@password", SqlDbType.NChar);
command.Parameters["@password"].Value = "abc";

command.Parameters.AddWithValue("@email", SqlDbType.NChar);
command.Parameters["@email"].Value = "abc";

command.ExecuteNonQuery();

谁能告诉我我做错了什么?

亲切的问候

编辑:

在另一行中,我正在创建一个新的 SQL 命令

var cmd = new SqlCommand(query, connection);

仍然无法正常工作,我在上面的代码中找不到任何错误。

【问题讨论】:

  • 你在哪里设置command.CommandText
  • 您是否尝试在不带@ 的情况下添加参数(在Parameters.Add 中)?例如。 command.Parameters.AddWithValue("id","abc")
  • ^ 他说你需要command.CommandText = query 否则你的查询根本与命令无关
  • 您说的是@password - 但您的意思是@saltedPasswordHash,对吗? ;p
  • DB 的错误信息是什么?恕我直言,您具有主唯一键,并且已经设置了具有此值的行。 Sou 尝试将 id 更改为 'abc' 以外的另一个字符串

标签: c# sql sql-server-express


【解决方案1】:

我假设你已经连接到你的数据库并且你不能使用 c# 来插入参数。

您没有在查询中添加参数。它应该看起来像:

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";

SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id","abc");
command.Parameters.Add("@username","abc");
command.Parameters.Add("@password","abc");
command.Parameters.Add("@email","abc");

command.ExecuteNonQuery();

更新:

using(SqlConnection connection = new SqlConnection(_connectionString))
{
    String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";

    using(SqlCommand command = new SqlCommand(query, connection))
    {
        command.Parameters.AddWithValue("@id", "abc");
        command.Parameters.AddWithValue("@username", "abc");
        command.Parameters.AddWithValue("@password", "abc");
        command.Parameters.AddWithValue("@email", "abc");

        connection.Open();
        int result = command.ExecuteNonQuery();

        // Check Error
        if(result < 0)
            Console.WriteLine("Error inserting data into Database!");
    }
}

【讨论】:

  • 请注意这里显示的Add() 的重载已经被弃用了一段时间。
  • 如果 Add() 已被弃用,那么新的插入方式是什么?
  • Add() 已弃用,请尝试 AddWithValue
  • 阅读这些 cmets 的注意事项:仅不推荐使用 Add(parameterName, value)Add(parameterName, sqlDbType) 和指定数据类型的类似方法非常好,不会去任何地方。例如,您仍然可以使用command.Parameters.Add("@username",SqlDbType.NChar).Value = "abc"。不推荐使用的是未指定参数的数据类型
【解决方案2】:

试试

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username, @password, @email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
    //a shorter syntax to adding parameters
    command.Parameters.Add("@id", SqlDbType.NChar).Value = "abc";

    command.Parameters.Add("@username", SqlDbType.NChar).Value = "abc";

    //a longer syntax for adding parameters
    command.Parameters.Add("@password", SqlDbType.NChar).Value = "abc";

    command.Parameters.Add("@email", SqlDbType.NChar).Value = "abc";

    //make sure you open and close(after executing) the connection
    connection.Open();
    command.ExecuteNonQuery();
}

【讨论】:

  • 我已经在使用完全相同的代码。我正在打开一个连接,使用查询和连接创建一个 SQLCommand 并执行相同的步骤。不知道为什么它不起作用
  • 很抱歉,没有看到您使用了 Add 方法。它现在确实起作用了。我不知道为什么这是唯一的方法,但我很高兴它终于奏效了。非常感谢
  • 如果您的 SqlConnection 对象在 using 块中,则无需调用 connection.Close()Dispose() 将为您执行此操作。
【解决方案3】:

“我的插入没有发生”的最常见错误(尤其是在使用 express 时)是:查看了错误的文件

如果您使用的是基于文件的 express(而不是强附加),那么项目文件夹中的文件(例如,c:\dev\myproject\mydb.mbd)是不是程序中使用的文件。当您构建时,该文件被复制 - 例如到c:\dev\myproject\bin\debug\mydb.mbd;您的程序在c:\dev\myproject\bin\debug\ 的上下文中执行,因此您需要在此处查看编辑是否真的发生了。确定检查:查询应用程序内的数据(插入后)。

【讨论】:

  • OP 说非参数化查询工作正常。由于abc 已经为用户名插入,如果为用户名设置了唯一键约束,数据库可能不会再次允许abc
  • @Kaf 嗯;有趣 - 但在这种情况下,您会认为唯一的约束违规是一个例外
【解决方案4】:
static SqlConnection myConnection;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        myConnection = new SqlConnection("server=localhost;" +
                                                      "Trusted_Connection=true;" +
             "database=zxc; " +
                                                      "connection timeout=30");
        try
        {

            myConnection.Open();
            label1.Text = "connect successful";

        }
        catch (SqlException ex)
        {
            label1.Text = "connect fail";
            MessageBox.Show(ex.Message);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {
        String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
        SqlCommand sqlcom = new SqlCommand(st, myConnection);
        try
        {
            sqlcom.ExecuteNonQuery();
            MessageBox.Show("insert successful");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

【讨论】:

    【解决方案5】:
    private void button1_Click(object sender, EventArgs e)
        {
            String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (@txtitemid,@txtitemname,@txtitemdesc,@txtitemqty)";
            try
            {
                using (SqlCommand command = new SqlCommand(query, con))
                {
    
                    command.Parameters.AddWithValue("@txtitemid", txtitemid.Text);
                    command.Parameters.AddWithValue("@txtitemname", txtitemname.Text);
                    command.Parameters.AddWithValue("@txtitemdesc", txtitemdesc.Text);
                    command.Parameters.AddWithValue("@txtitemqty", txtitemqty.Text);
    
    
                    con.Open();
                    int result = command.ExecuteNonQuery();
    
                    // Check Error
                    if (result < 0)
                        MessageBox.Show("Error");
    
                    MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    con.Close();
                    loader();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                con.Close();
            }
        }
    

    【讨论】:

      【解决方案6】:
      public static string textDataSource = "Data Source=localhost;Initial 
      Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";
      public static bool ExtSql(string sql) {
          SqlConnection cnn;
          SqlCommand cmd;
          cnn = new SqlConnection(textDataSource);
          cmd = new SqlCommand(sql, cnn);
          try {
              cnn.Open();
              cmd.ExecuteNonQuery();
              cnn.Close();
              return true;
          }
          catch (Exception) {
              return false;
          }
          finally {
              cmd.Dispose();
              cnn = null;
              cmd = null; 
          }
      }
      

      【讨论】:

        【解决方案7】:

        我刚刚为此写了一个可重用的方法,这里没有可重用方法的答案,所以为什么不分享...
        这是我当前项目的代码:

        public static int ParametersCommand(string query,List<SqlParameter> parameters)
        {
            SqlConnection connection = new SqlConnection(ConnectionString);
            try
            {
                using (SqlCommand cmd = new SqlCommand(query, connection))
                {   // for cases where no parameters needed
                    if (parameters != null)
                    {
                        cmd.Parameters.AddRange(parameters.ToArray());
                    }
        
                    connection.Open();
                    int result = cmd.ExecuteNonQuery();
                    return result;
                }
            }
            catch (Exception ex)
            {
                AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
                return 0;
                throw;
            }
        
            finally
            {
                CloseConnection(ref connection);
            }
        }
        
        private static void CloseConnection(ref SqlConnection conn)
        {
            if (conn.State != ConnectionState.Closed)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        

        【讨论】:

          【解决方案8】:
          class Program
          {
              static void Main(string[] args)
              {
                  string connetionString = null;
                  SqlConnection connection;
                  SqlCommand command;
                  string sql = null;
          
                  connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
                  sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
                  connection = new SqlConnection(connetionString);
          
                  try
                  {
                      connection.Open();
                      Console.WriteLine(" Connection Opened ");
                      command = new SqlCommand(sql, connection);                
                      SqlDataReader dr1 = command.ExecuteReader();         
          
                      connection.Close();
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine("Can not open connection ! ");
                  }
              }
          }
          

          【讨论】:

          • 对于 Inserting 你不需要使用 execute reader ,而不是 reader 我们应该使用 ExecuteNonquery 来进行 insert , update 和 delete 来验证受影响的行.. @theLaw 解释了使用块和参数化查询.. 参数化查询在 sql 注入的情况下非常有效,如果我们使用 Using Block,我们不需要担心关闭连接..
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-06
          • 1970-01-01
          相关资源
          最近更新 更多