【问题标题】:Syntax Error - INSERT INTO Statement语法错误 - INSERT INTO 语句
【发布时间】:2016-12-16 12:57:02
【问题描述】:

我正在制作一个表格来将帐户添加到我的登录应用程序 如果您能提供帮助,那就太好了。

我只有 11 岁,所以这可能是个愚蠢的问题!

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

namespace Login_Viper_Safe
{
    public partial class Form3 : Form
    {
        private OleDbConnection connection = new OleDbConnection();
        public Form3()
        {
            InitializeComponent();
            connection.ConnectionString =   @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\SillyTen9\Documents\UserDatabase.accdb; Persist Security Info=False;";
    }

    private void Form3_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "INSERT INTO UserDatabase ([Username], [Password], FirstName, LastName) VALUSES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')";
            command.ExecuteNonQuery();
            MessageBox.Show("Signed Up!");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error " + ex);
        }
    }
}

【问题讨论】:

  • VALUSES 应该是VALUES
  • 旁注: 1. 使用参数作为您的值。 2. 尽量不要使用类作用域连接,而是在需要时创建它们然后关闭它们。 3. 创建连接时将连接包装在using 块中,以及实现IDisposable 的任何其他类型,例如OleDbCommand。 4. 将您的连接字符串放入app.config 并在需要时从那里检索。
  • 尽量避免使用 SQL,并使用参数化查询来避免 SQL 注入和其他讨厌的事情。 stackoverflow.com/questions/7505808/…

标签: c# database


【解决方案1】:

你的值有错误(额外):

 "INSERT INTO UserDatabase ([Username], [Password], FirstName, LastName) VALUES( ...

使用参数也很重要:

command.CommandText = "INSERT INTO UserDatabase ([Username], [Password], FirstName, LastName) VALUES (@param1,@param2,@param3,@param4)";
command.Parameters.AddWithValue("@param1",textBox1.Text);
command.Parameters.AddWithValue("@param2",textBox2.Text);
command.Parameters.AddWithValue("@param3",textBox3.Text);
command.Parameters.AddWithValue("@param4",textBox4.Text);
...

【讨论】:

    【解决方案2】:

    您在插入查询中输入错误,其值不是 VALUSES

    command.CommandText = "INSERT INTO UserDatabase ([Username], [Password], FirstName, LastName) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      相关资源
      最近更新 更多