简体   繁体   English

Catch SqlException尝试通过按钮单击事件向sql数据库添加数据时抛出错误无效语法

[英]Catch SqlException throwing error invalid syntax when trying to add data to sql database through button click event

I'm developing an application for a school project but am having trouble with adding data to the sql database. 我正在开发一个学校项目的应用程序,但是在向sql数据库添加数据时遇到了麻烦。 The plan is the user will click a button to 'add' data, this opens a new form with various textboxes for data to be input. 计划是用户将单击一个按钮以“添加”数据,这将打开一个新表单,其中包含各种文本框以输入数据。 When satisfied the user clicks 'add details' and these are then added to the sql database. 当用户满意时,单击“添加详细信息”,然后将这些添加到sql数据库中。 The issue is the try catch keeps returning an error and I'm at a loss as to why, possibly an easy fix for someone with fresh eyes. 问题是尝试捕获不断返回错误,我不知道为什么,可能是一个容易修复的新眼睛的人。 The code is as follows: 代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace CarsULike
{
public partial class AddCust : Form
{
    public AddCust()
    {
        InitializeComponent();
    }

    private void AddCust_Load(object sender, EventArgs e)
    {

    }

    private void AddCustBtn_Click(object sender, EventArgs e)
    {
        if (FirstNameTxtBox.Text == "")
        {
            MessageBox.Show("Please enter a First Name");
        }
        else if (SurnameTxtBox.Text == "")
        {
            MessageBox.Show("Please enter a Surname");
        }
        else if (TitleTxtBox.Text == "")
        {
            MessageBox.Show("Please enter a Title");
        }
        else if (Address1TxtBox.Text == "")
        {
            MessageBox.Show("Please enter an address");
        }
        else if (TownCityTxtBox.Text == "")
        {
            MessageBox.Show("Please enter a Town/City");
        }
        else if (PostCodeTxtBox.Text == "")
        {
            MessageBox.Show("Please enter a Postcode");
        }
        else
        {
            //stores the values entered as variables
            string firstName = FirstNameTxtBox.Text;
            string surname = SurnameTxtBox.Text;
            string title = TitleTxtBox.Text;
            string address1 = Address1TxtBox.Text;
            string address2 = Address2TxtBox.Text;
            string townCity = TownCityTxtBox.Text;
            string postCode = PostCodeTxtBox.Text;
            string mobPhone = MobPhoneTxtBox.Text;
            string homePhone = HomePhoneTxtBox.Text;
        }

        //establishes a connection with the database
        SqlConnection connection = new SqlConnection(@"Data Source=Lee-PC\SQLEXPRESS; Initial Catalog=CarsULike_P116274;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();
        //SqlDataReader datareader;
        string sql;

        try
        {
            // this query is for insertion into the Customer table
            sql = "INSERT INTO Customer (FirstName, Surname, Title, AddressLine1, AddressLine2, TownCity, PostCode, EmailAddress, MobilePhoneNo, HomePhoneNo)";
            sql += String.Format("VALUES, @FirstName, @Surname, @Title, @AddressLine1, @AddressLine2, @TownCity, @PostCode, @EmailAddress, @MobilePhoneNo, @HomePhoneNo)");

            cmd = new SqlCommand(sql, connection);
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;

            cmd.Parameters.AddWithValue("@FirstName", FirstNameTxtBox.Text);
            cmd.Parameters.AddWithValue("@Surname", SurnameTxtBox.Text);
            cmd.Parameters.AddWithValue("@Title", TitleTxtBox.Text);
            cmd.Parameters.AddWithValue("@AddressLine1", Address1TxtBox.Text);
            cmd.Parameters.AddWithValue("@AddressLine2", Address2TxtBox.Text);
            cmd.Parameters.AddWithValue("@TownCity", TownCityTxtBox.Text);
            cmd.Parameters.AddWithValue("@PostCode", PostCodeTxtBox.Text);
            cmd.Parameters.AddWithValue("@EmailAddress", MobPhoneTxtBox.Text);
            cmd.Parameters.AddWithValue("@MobilePhoneNo", HomePhoneTxtBox.Text);
            cmd.Parameters.AddWithValue("@HomePhoneNo", HomePhoneTxtBox.Text);

            connection.Open(); //opens connection
            cmd.ExecuteNonQuery(); //writes to the database
            MessageBox.Show("Details Added", "Successful");
        }

        catch (SqlException ex)
        {
            throw new Exception("Error adding details", ex);

        }
        finally
        {
            connection.Close(); // Close connection
        }
    }

    private void CancelAddCustBtn_Click(object sender, EventArgs e)
    {
        this.Close();   // Close current form
    }
}

I've had a look around but can't seem to find what I'm looking for..or I just don't know what I'm looking for! 我已经环顾四周但似乎无法找到我正在寻找的东西..或者我只是不知道我在寻找什么!

Change 更改

"VALUES, @FirstName, @Surname, @Title, @AddressLine1, @AddressLine2, @TownCity, @PostCode, @EmailAddress, @MobilePhoneNo, @HomePhoneNo)"

To

"VALUES ( @FirstName, @Surname, @Title, @AddressLine1, @AddressLine2, @TownCity, @PostCode, @EmailAddress, @MobilePhoneNo, @HomePhoneNo)"

Change comma to open-paren. 将逗号更改为open-paren。

There could be other errors, but this is definitely one. 可能还有其他错误,但这肯定是一个错误。

Also, you will probably want to adjust your catch-statement to make sure that you are seeing the exact sql error. 此外,您可能希望调整catch语句以确保您看到确切的sql错误。 Normally, SQL Exceptions (or inner exceptions) will give you a pretty good clue about what is wrong with the SQL code, or if there is a problem with the connections tring. 通常,SQL异常(或内部异常)将为您提供有关SQL代码错误或连接问题是否存在问题的非常好的线索。

In this part 在这一部分

"VALUES, @FirstName

You are failing to open a parenthesis which you are later closing, that's the error. 您未能打开稍后关闭的括号,这就是错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试连接到SQL Server数据库时出现“ SqlException未处理”错误 - 'SqlException was unhandled' error when trying to connect to SQL Server database 尝试向数据库插入行时,SQL语法无效 - Invalid SQL syntax when trying to insert a row to the database System.Data.SqlClient.SqlException:'尝试在数据库中插入数据时无效的对象名称(C#,Visual Studio) - System.Data.SqlClient.SqlException: 'Invalid object name when trying to insert data in database (C#, Visual Studio) 尝试在按钮单击事件上的列表框中选择所有项目时出错 - Error when trying to select all items in listbox on button click event 尝试将数据添加到数据库时出错 - Getting an error when trying to add data into database 尝试使用SQL将数据插入数据库时​​出现“无效的列名” - “Invalid column name” when trying to insert data into database using SQL 尝试通过C#应用程序将数据插入SQL Server数据库时出错 - Error when trying to insert data to a SQL Server database through a C# application 抛出异常:尝试简单插入 SQL 服务器数据库时 System.Data.dll 中的“System.Data.SqlClient.SqlException” - Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll when trying to make simple insertion into SQL Server database 从SQL数据库检索数据时出现“无效的列名”错误? - “invalid column name” error when retrieving data from SQL database? SQL命令语法错误:System.Data.SqlClient.SqlException:','附近的语法不正确。 - Sql commands Syntax Error: System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM