通过 C# 使用 ado.net 将值插入 SQL Server 数据库 [英] Inserting values into a SQL Server database using ado.net via C#

查看:16
本文介绍了通过 C# 使用 ado.net 将值插入 SQL Server 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的程序来将值插入到表 [regist] 中,但我不断收到错误

I have created a simple program to insert values into the table [regist], but I keep getting the error

')' 附近的语法不正确

关于cmd.ExecuteNonQuery();:

 private void button1_Click(object sender, EventArgs e)
 {
      SqlConnection cn = new SqlConnection("Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;");

      SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact, " + ") VALUES (" + " @textBox1.Text, @textBox2.Text, @textBox3.Text, @textBox4.Text, @comboBox1.Text,@comboBox2.Text,@textBox7.Text" + ")", cn);

      cn.Open();
      cmd.ExecuteNonQuery();
      cn.Close();
}

我是新手,我真的很困惑.

I am new to this and I am really confused.

推荐答案

正如我在评论中所说 - 您应该始终在查询中使用参数 - 永远不要连接在一起您自己的 SQL 语句.

As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.

另外:我建议将点击事件处理程序与实际代码分开以插入数据.

Also: I would recommend to separate the click event handler from the actual code to insert the data.

所以我会将你的代码重写为类似

So I would rewrite your code to be something like

在您网页的代码隐藏文件中 (yourpage.aspx.cs)

In your web page's code-behind file (yourpage.aspx.cs)

private void button1_Click(object sender, EventArgs e)
{
      string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";

      InsertData(connectionString,
                 textBox1.Text.Trim(),  -- first name
                 textBox2.Text.Trim(),  -- last name
                 textBox3.Text.Trim(),  -- user name
                 textBox4.Text.Trim(),  -- password
                 Convert.ToInt32(comboBox1.Text),  -- age
                 comboBox2.Text.Trim(), -- gender
                 textBox7.Text.Trim() );  -- contact
}

在其他一些代码中(例如 databaselayer.cs):

In some other code (e.g. a databaselayer.cs):

private void InsertData(string connectionString, string firstName, string lastname, string username, string password
                        int Age, string gender, string contact)
{
    // define INSERT query with parameters
    string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " + 
                   "VALUES (@FirstName, @Lastname, @Username, @Password, @Age, @Gender, @Contact) ";

    // create connection and command
    using(SqlConnection cn = new SqlConnection(connectionString))
    using(SqlCommand cmd = new SqlCommand(query, cn))
    {
        // define parameters and their values
        cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = firstName;
        cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = lastName;
        cmd.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = userName;
        cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = password;
        cmd.Parameters.Add("@Age", SqlDbType.Int).Value = age;
        cmd.Parameters.Add("@Gender", SqlDbType.VarChar, 50).Value = gender;
        cmd.Parameters.Add("@Contact", SqlDbType.VarChar, 50).Value = contact;

        // open connection, execute INSERT, close connection
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
    }
}

这样的代码:

  • 不易受到 SQL 注入攻击
  • 在 SQL Server 上的性能要好得多(因为查询被解析为执行计划一次,然后被缓存并稍后重用)
  • 将事件处理程序(代码隐藏文件)与您的实际数据库代码(将内容放在它们所属的位置)分离 - 帮助避免超重"代码隐藏与大量意大利面条代码,从处理 UI 事件到数据库访问 -不是好设计!)

这篇关于通过 C# 使用 ado.net 将值插入 SQL Server 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆