【问题标题】:whats wrong with this code??(c1.CommandText = "insert into stu values='" + textBox1 + "','" + textBox2 + "'";)这段代码有什么问题??(c1.CommandText =“插入stu值='”+ textBox1 +“','”+ textBox2 +“'”;)
【发布时间】:2014-05-18 09:06:22
【问题描述】:

嗨,我用 C# 编写了一个简单的代码,用于在 SQLDatabase 上插入一些名称

这是我的完整代码

我有这个错误

无法在服务器上连接


namespace CsharpProject
{
    public partial class From2 : Form
    {
        public From2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string s1 = "Data Source=.;Initial Catalog=test1;Integrated Security=True";
            SqlConnection sc1 = new SqlConnection(s1);
            SqlCommand c1 = new SqlCommand("",sc1);
            c1.CommandText = "insert into stu values='" + textBox1 + "','" + textBox2 + "'";
            try
            {
                sc1.Open();
                if (c1.ExecuteNonQuery() == 1)
                {
                    MessageBox.Show("successes");
                    textBox1.Focus();

                }
                else
                {
                    MessageBox.Show("Error ");
                    textBox2.Focus();
                }
            }
            catch
            {
                MessageBox.Show("Unable to connect on server ");
                textBox2.Focus();
            }
            finally{
            sc1.Close();
            }

        }
    }
}

我认为我的问题在这里,但我无法解决它

c1.CommandText = "insert into stu values='" + textBox1 + "','" + textBox2 + "'";

请帮助我 谢谢

【问题讨论】:

  • 查询语法错误这里是正确的 synatx:insert into stu values(val,val2)
  • Unable to connect to server - 很抱歉,没有办法与构建 SQL 查询相关。想想错误在说什么。 Connect...嗯..也许Connection...
  • 连接字符串也是错误的,这是该异常的原因
  • @HenkHolterman 啊是的.. 很公平。我想我应该读过代码。
  • 我使用 catch (ex) 并显示 TEXT:insert

标签: c# sql-server


【解决方案1】:

你的代码应该是..

c1.CommandText = "insert into stu values('" + textBox1.Text + "','" + textBox2.Text + "')";

但我建议你使用参数化 SQL 查询来避免 SQL 注入攻击

这是您的查询在参数化后的样子

c1.CommandText = "insert into stu values(@textBox1, @textBox2)";

c1.Parameters.AddWithValue("@textBox1", textBox1.Text)
c1.Parameters.AddWithValue("@textBox2", textBox2.Text)

这是一个有用的链接,可帮助您了解有关参数化查询的更多信息。

Using Parameterized queries to prevent SQL Injection Attacks in SQL Server

【讨论】:

    【解决方案2】:

    如果您有多个 sql 实例,则应在连接字符串的源属性中的 .\ 之后添加实例名称。

    如果你确定 conectionString 试试这个:

    c1.CommandText = string.Format("insert into stu (col1, col2) values ({0}, {1})", textBox1, textBox2);
    

    【讨论】:

      【解决方案3】:

      你缺少一个右括号

      c1.CommandText = "insert into stu values('" + textBox1 + "','" + textBox2 + "')";
      

      【讨论】:

        【解决方案4】:

        真正的问题是您没有参数化您的 SQL 查询。 (即:http://buddylindsey.com/sql-parameters-in-c/)这使您容易受到 SQL 注入攻击 - 请参阅 http://bobby-tables.com/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-04-25
          • 2018-09-09
          相关资源
          最近更新 更多