如何修复保存按钮

时间:2019-02-17 17:41:09

标签: c# ms-access oledbcommand

我为自己的乐趣写了一个代码。 我可以访问数据文件“ mdb”,并从gridview在gridview上显示他,然后选择行并在文本框中显示。 我编辑文本框,然后尝试按“保存”按钮,并向我显示错误消息。 我做错了什么? 保存按钮没有保存并向我显示错误消息。

添加图片和我的代码:

Error msg

gridview+textbox

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 Center image description hereDHW
{
    public partial class Form2 : Form
    {
        private OleDbConnection connection = new OleDbConnection();
        public Form2()
        {
            InitializeComponent();
            connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\RBA\Desktop\123\users1.mdb;
Persist Security Info=False;";
        }

        private void button9_Click(object sender, EventArgs e)
        {
            this.Close();
            Form1 f1 = new Form1();
            f1.Show();

        }


        private void btn_save_Click(object sender, EventArgs e)
        {
            try
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                command.CommandText = "insert into GRL1 (NoBoard,Site,Group,Kind,Unit) values ('" + txt_noboard.Text + "','" + txt_site.Text + "','" + txt_group.Text + "','" + txt_kind.Text + "','" + txt_unit.Text + "',)";

                command.ExecuteNonQuery();
                MessageBox.Show("Data Saved");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error  " + ex);
            }
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'users1DataSet.GRL1' table. You can move, or remove it, as needed.
            this.gRL1TableAdapter.Fill(this.users1DataSet.GRL1);

        }

        private void btn_loadGR_Click(object sender, EventArgs e)
        {
            try
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                string query = "select * from GRL1";
                command.CommandText = query;

                OleDbDataAdapter da = new OleDbDataAdapter(command);
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;

                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error  " + ex);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                string query = "select * from GRS1";
                command.CommandText = query;

                OleDbDataAdapter da = new OleDbDataAdapter(command);
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;

                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error  " + ex);
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];

                txt_noboard.Text = row.Cells[0].Value.ToString();
                txt_site.Text = row.Cells[1].Value.ToString();
                txt_group.Text = row.Cells[2].Value.ToString();
                txt_kind.Text = row.Cells[3].Value.ToString();
                txt_unit.Text = row.Cells[4].Value.ToString();
                txt_com.Text = row.Cells[5].Value.ToString();
            }
        }


    }
}

1 个答案:

答案 0 :(得分:0)

您的sql文本中有错字。右括号前有一个逗号。但是,由于在MS-Access(组)中使用保留关键字也会导致错误。您需要在该名称前后加上方括号。

最后,不要使用字符串连接来构建sql命令,而要始终使用参数。
这样可以避免sql注入攻击,并消除了解析输入的问题(例如,如果输入文本中有一个单引号,则整个查询将再次由于语法错误而失败)

private void btn_save_Click(object sender, EventArgs e)
{
    try
    {
        using(OleDbConnection connection = new OleDbConnection(....con string...))
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            // Notice how Group field is between square brackets.
            // If you can I suggest to change the name of this field
            string cmdText = @"insert into GRL1 (NoBoard,Site,[Group],Kind,Unit) 
                          values (@nob, @sit, @grp, @knd, @uni)";
            command.CommandText = cmdText;
            // Is NoBoard an integer? If yes you should pass an integer not a string
            command.Parameters.Add("@nob", OleDbType.Integer).Value = Convert.ToInt32(txt_noboard.Text);
            command.Parameters.Add("@sit", OleDbType.VarWChar).Value = txt_site.Text;
            command.Parameters.Add("@grp", OleDbType.VarWChar).Value = txt_group.Text;
            command.Parameters.Add("@knd", OleDbType.VarWChar).Value = txt_kind.Text;
            command.Parameters.Add("@uni", OleDbType.VarWChar).Value = txt_unit.Text;
            command.ExecuteNonQuery();
            MessageBox.Show("Data Saved");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error  " + ex);
    }
}

参数集合中填充了查询文本所需的值。请注意,我不完全知道数据库中列的数据类型。参数OleDbType应该与期望的类型完全匹配,以避免Type Mismatch异常

最后提示。需要时应创建,打开和关闭连接。不要保留全局连接对象。由于ADO.NET使用一种称为“连接池”的技术