Я работаю над приложением базы данных в C#, которое подключается к базе данных Microsoft Access. Теперь я работал, где, когда я нажимаю «Сохранить», он сказал бы, что данные были успешно введены, но я узнал, что он фактически не вводил данные в базу данных.Получение ошибки исключения: Ошибка синтаксиса (отсутствующий оператор) в выражении запроса
Так с помощью прекрасных людей здесь StackOverflow я смог выяснить, что мне нужно сделать, чтобы заставить его работать, но теперь я получаю необработанное исключение говоря следующее:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error (missing operator) in query expression '@[Guest First Name]'.
Мне любопытно, где проблема. Это исключение вызывается, когда оно достигает com.ExecuteNonQuery(); строка следующего кода:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.OleDb;
using System.Data;
using System.ComponentModel;
namespace ParkingDatabase
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
using (OleDbConnection DBConnect = new OleDbConnection())
{
DBConnect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\bkoso\documents\visual studio 2015\Projects\ParkingDatabase\ParkingDatabase\ParkingData.accdb";
using (OleDbCommand com = new OleDbCommand("INSERT INTO [Guest Info]([Guest First Name], [Guest Last Name], [Room Number], [Departure Date], [Return Date], [Vehicle Colour], [Vehicle Make], [Plate Number], [Contact First Name], [Contact Last Name], [Contact Number], [Contact Email], [Tag Number]) Values(@[Guest First Name], @[Guest Last Name], @[Room Number], @[Departure Date], @[Return Date], @[Vehicle Colour], @[Vehicle Make], @[Plate Number], @[Contact First Name], @[Contact Last Name], @[Contact Email], @[Contact Email], @[Tag Number])", DBConnect))
//the section below was recently updated
{
com.Parameters.AddWithValue("@GuestFirstName", txtBxGstFName.Text);
com.Parameters.AddWithValue("@GuestLastName", txtBxGstLName.Text);
com.Parameters.AddWithValue("@RoomNumber", txtBxRm.Text);
com.Parameters.AddWithValue("@DepartureDate", txtBxDDate.Text);
com.Parameters.AddWithValue("@ReturnDate", txtBxRDate.Text);
com.Parameters.AddWithValue("@VehicleColour", txtBxVColour.Text);
com.Parameters.AddWithValue("@VehicleMake", txtBxVMake.Text);
com.Parameters.AddWithValue("@PlateNumber", txtBxPlate.Text);
com.Parameters.AddWithValue("@ContactFirstName", txtBxContactFName.Text);
com.Parameters.AddWithValue("@ContactLastName", txtBxContactLName.Text);
com.Parameters.AddWithValue("@ContactNumber", txtBxPhone.Text);
com.Parameters.AddWithValue("@ContactEmail", txtBxEmail.Text);
com.Parameters.AddWithValue("@TagNumber", txtBxTag.Text);
DBConnect.Open();
com.ExecuteNonQuery();
DBConnect.Close();
}
if (DBConnect.State == ConnectionState.Open)
{
//com.ExecuteNonQuery();
MessageBox.Show("Guest Information Saved Successfully");
txtBxGstFName.Text = "";
txtBxGstLName.Text = "";
txtBxRm.Text = "";
txtBxDDate.Text = "";
txtBxRDate.Text = "";
txtBxVColour.Text = "";
txtBxVMake.Text = "";
txtBxPlate.Text = "";
txtBxContactFName.Text = "";
txtBxContactLName.Text = "";
txtBxPhone.Text = "";
txtBxEmail.Text = "";
txtBxTag.Text = "";
}
}
}
private void btnClear_Click(object sender, RoutedEventArgs e)
{
txtBxGstFName.Text = "";
txtBxGstLName.Text = "";
txtBxRm.Text = "";
txtBxDDate.Text = "";
txtBxRDate.Text = "";
txtBxVColour.Text = "";
txtBxVMake.Text = "";
txtBxPlate.Text = "";
txtBxContactFName.Text = "";
txtBxContactLName.Text = "";
txtBxPhone.Text = "";
txtBxEmail.Text = "";
txtBxTag.Text = "";
}
private void btnView_Click(object sender, RoutedEventArgs e)
{
}
private void btnSame_Click(object sender, RoutedEventArgs e)
{
}
private void txtBoxGuestFirstName_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
}
}
}
Попробуйте использовать пробелы между словами в параметрах - я не уверен, что SQL поддерживает пробелы между словами в параметрах. I.e., @GuestFirstName вместо @ [Имя гостя]. – Tim
Возможно [это] (http://stackoverflow.com/questions/21636957/access-form-syntax-error-missing-operator-in-query-expression) может помочь. –
, так почему '[]' в параметрах избавляется от пробелов. Также попробуйте заменить раздел значений на '?,?,?,? ... и т. Д. Также есть несколько примеров того, как вставлять в Access БД, использующий C#, пытается показать больше усилий в отношении выполнения поиска в Google, также является хорошим примером http://stackoverflow.com/questions/5893837/using-parameters-inserting-data-into-access-database – MethodMan