ExecuteNonQuery 显示错误

ExecuteNonQuery showing error

我更新了代码并为语句设置了参数。除了更新语句之外,一切都按应有的方式正常工作,没有给出错误并且它完成了 else 语句但它不更新数据库。 'else' 语句中的更新代码是否有误或其他内容? 谢谢

MainWindow.xaml.cs:

   using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;

namespace WpfApplication12
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        OleDbConnection con;
        DataTable dt;


        public MainWindow()
        {
            InitializeComponent();
            con = new OleDbConnection();
            con.ConnectionString = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "\MONDIAL.accdb";
            BindGrid();
        }

        private void BindGrid()
        {
            OleDbCommand cmd = new OleDbCommand();
            if (con.State != ConnectionState.Open)
                con.Open();
            cmd.Connection = con;
            cmd.CommandText = "select * from Country";
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            dt = new DataTable();
            da.Fill(dt);
            gvData.ItemsSource = dt.AsDataView();

            if (dt.Rows.Count > 0)
            {
                gvData.Visibility = System.Windows.Visibility.Visible;

            }
            else
            {
                gvData.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            OleDbCommand cmd = new OleDbCommand();
            if (con.State != ConnectionState.Open)
                con.Open();
            cmd.Connection = con;

            if (txtCode.Text != "")
            {
                if (txtCode.IsEnabled == true)
                {
                    if (txtCountryName.Text != "")
                    {
                        cmd.CommandText = "INSERT INTO Country" + "([CountryName],[Code],[Capital],[Province],[Area],[Population])" +
                            "VALUES (@CountryName, @Code, @Capital, @Province, @Area, @Population)";
                        cmd.Parameters.AddRange(new OleDbParameter[]
                        {
                            new OleDbParameter("@CountryName", txtCountryName.Text),
                            new OleDbParameter("@Code", txtCode.Text),
                            new OleDbParameter("@Capital", txtCapital.Text),
                            new OleDbParameter("@Province", txtProvince.Text),
                            new OleDbParameter("@Area", txtArea.Text),
                            new OleDbParameter("@Population", txtPopulation.Text),
                        });
                            cmd.ExecuteNonQuery();
                            BindGrid();
                            MessageBox.Show("Country Added Successfully..");
                            ClearAll();
                    } 
                    else
                    {
                        MessageBox.Show("Please add a code");
                    }
                }
                else
                {
                    DataRowView row = (DataRowView)gvData.SelectedItems[0];
                    cmd.CommandText = "UPDATE [Country] SET [CountryName] = @CountryName, [Capital ]= @Capital, [Province] = @Province, [Area] = @Area, [Population] = @Population WHERE [Code] = @Code";
                        cmd.Parameters.AddRange(new OleDbParameter[]
                        {
                            new OleDbParameter("@Code",  txtCode.Text),
                            new OleDbParameter("@CountryName", txtCountryName.Text),   
                            new OleDbParameter("@Capital", txtCapital.Text),
                            new OleDbParameter("@Province", txtProvince.Text),
                            new OleDbParameter("@Area", txtArea.Text),
                            new OleDbParameter("@Population", txtPopulation.Text),
                        });
                            cmd.ExecuteNonQuery();
                            BindGrid();
                            MessageBox.Show("Country Updated Successfully..");
                            ClearAll();
                    } 
            }
            else
            {
                MessageBox.Show("add country name");
            }
        }

             private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            ClearAll();
        }

            private void ClearAll()
             {
                 txtCountryName.Text = "";
                 txtCode.Text = "";
                 txtCapital.Text = "";
                 txtProvince.Text = "";
                 txtArea.Text = "";
                 txtPopulation.Text = "";
                 btnAdd.Content = "Add";
                 txtCode.IsEnabled = true;

             }

            private void btnEdit_Click(object sender, RoutedEventArgs e)
            {
                if (gvData.SelectedItems.Count > 0)
                {
                    DataRowView row = (DataRowView)gvData.SelectedItems[0];
                    txtCountryName.Text = row["CountryName"].ToString();
                    txtCode.Text = row["Code"].ToString();
                    txtCapital.Text = row["Capital"].ToString();
                    txtProvince.Text = row["Province"].ToString();
                    txtArea.Text = row["Area"].ToString();
                    txtPopulation.Text = row["Population"].ToString();
                    btnAdd.Content = "Update";
                    txtCode.IsEnabled = false;
                }
                else
                {
                    MessageBox.Show("please select a country from the list");
                }
            }

private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (gvData.SelectedItems.Count > 0)
            {



                DataRowView row = (DataRowView)gvData.SelectedItems[0];

                OleDbCommand cmd = new OleDbCommand();
                if (con.State != ConnectionState.Open)
                    con.Open();
                cmd.Connection = con;
                cmd.CommandText = "DELETE FROM [Country] WHERE [Code]= @CodeRow";
                cmd.Parameters.AddRange(new OleDbParameter[]
                    {
                        new OleDbParameter("@CodeRow", row["Code"].ToString())
                    });
                cmd.ExecuteNonQuery();
                BindGrid();
                MessageBox.Show("country Deleted Successfully...");
                ClearAll();
            }
            else
            {
                MessageBox.Show("Please Select Any country From List...");
            }
        }

        //Exit
        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }
    }
}

MainWindow.xaml:

<Window x:Class="WpfApplication12.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="1000" Width="1000">
<Window.Resources>
    <Style TargetType="TextBlock">
        <Setter Property="FontSize" Value="20"/>
        <Setter Property="Width" Value="160"/>
        <Setter Property="Margin" Value="10"/>
    </Style>
    <Style TargetType="TextBox">
        <Setter Property="FontSize" Value="20"/>
        <Setter Property="Width" Value="250"/>
        <Setter Property="Margin" Value="10"/>
    </Style>
</Window.Resources>
<DockPanel Name="dockMain" VerticalAlignment="Top" HorizontalAlignment="Center" LastChildFill="False">
    <StackPanel>
        <WrapPanel>
            <TextBlock Text="Country Name"/>
            <TextBox Name="txtCountryName"/>
        </WrapPanel>
        <WrapPanel>
            <TextBlock Text="Code"/>
            <TextBox Name="txtCode"/>
        </WrapPanel>
        <WrapPanel>
            <TextBlock Text="Capital"/>
            <TextBox Name="txtCapital"/>
        </WrapPanel>
        <WrapPanel>
            <TextBlock Text="Province"/>
            <TextBox Name="txtProvince"/>
        </WrapPanel>
        <WrapPanel>
            <TextBlock Text="Area"/>
            <TextBox Name="txtArea"/>
        </WrapPanel>
        <WrapPanel>
            <TextBlock Text="Population"/>
            <TextBox Name="txtPopulation"/>
        </WrapPanel>
        <WrapPanel Margin="0" HorizontalAlignment="Center" Height="59">
            <Button Name="btnAdd" Content="Add" FontSize="25" Width="120" Margin="5" Click="btnAdd_Click" />
            <Button Name="btnEdit" Content="Edit" FontSize="25" Width="120" Margin="5" Click="btnEdit_Click" />
            <Button Name="btnDelete" Content="Delete" FontSize="25" Width="120" Margin="5" Click="btnDelete_Click" />
            <Button Name="btnCancel" Content="Cancel" FontSize="25" Width="120" Margin="5" Click="btnCancel_Click" />
            <Button Name="btnExit" Content="Exit" FontSize="25" Width="120" Margin="5" Background="#400000" Foreground="Bisque" Click="btnExit_Click" />
        </WrapPanel>
        <ScrollViewer ScrollViewer.VerticalScrollBarVisibility="Auto">
            <WrapPanel Margin="20" HorizontalAlignment="Center">
                <DataGrid AutoGenerateColumns="True" Name="gvData" IsReadOnly="False" SelectionMode="Single" FontSize="15" Padding="5" Background="Black" Height="525" Width="775" />
            </WrapPanel>
        </ScrollViewer>
    </StackPanel>
</DockPanel>

连接 SQL 语句时,您在字段值中遗漏了一些分隔符,例如

VALUES(" + txtCountryName.Text + ",

应该是

VALUES('" + txtCountryName.Text + "',

根据数据库中的类型检查其他查询,"update" 查询似乎也遇到同样的问题。

顺便说一句,你永远不应该像你正在做的那样在 SQL 语句 中连接值,这会使你的应用程序暴露于一个常见的漏洞,称为 SQL 注入,以及性能不佳。请改用参数。 看这里:

http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06