简体   繁体   English

如何在数据库中引入数据并在DataGridView中查看日期?

[英]How can I introduce data in database and to view dates in DataGridView?

namespace Test
{
    public partial class Form1 : Form
    { 
        OleDbConnection cn;

        private String connParam = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Diana\Documents\Visual Studio 2012\Projects\Test\Test\baza.mdb;Persist Security Info=False";
        public Form1()
        {
            cn = new OleDbConnection(connParam);   
            InitializeComponent();
        }  
        DataSet ds;
        OleDbDataAdapter da;

        private void Form1_Load(object sender, EventArgs e)
        {
            cn.Open();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(textBox1.Text) > 36)
            {          
                MessageBox.Show("Insert a valid data");

                OleDbCommand comm = cn.CreateCommand();
                comm.CommandText = "insert into ins_number (numb) values ('" + this.textBox1.Text + "');";
                comm.ExecuteNonQuery();
                da = new OleDbDataAdapter("select Number,[Red],[Black],[1_18],[19_36],[Even],[Odd],[1Column],[2Column],[3Column],[1Dozen],[2Dozen],[3Dozen] from [number],[ins_number] where number=numb order by [Id_Numb] desc", connParam);
                ds = new DataSet();
                da.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];        
            }
        }
    }
}

When I click ok, I need first to add data in database and to view dates in dataGridView but I don't see last value which I introduce, I see the first data when I add second. 当我单击确定时,我首先需要在数据库中添加数据并在dataGridView中查看日期,但我没有看到我介绍的最后一个值,当我添加第二个时,我看到第一个数据。 How can I make to view it in the same time when I click ok? 当我点击确定时,如何在同一时间查看它?

You should really change a lot of things in the code above. 你应该在上面的代码中真正改变很多东西。

  • First, do not keep in class global variables your connection. 首先,不要在类全局变量中保留您的连接。 It is an expensive resource and you should really open, use and release it only when you need it 它是一种昂贵的资源,您应该只在需要时打开,使用和释放它
  • Second, you should use parameterized query instead of string concatenations. 其次,您应该使用参数化查询而不是字符串连接。 This will avoid parsing problems, sql injections and your query will be more readable 这将避免解析问题,sql注入和您的查询将更具可读性
  • Third, embedding the variable name inside the string command doesn't transfor the variable in the actual number, you should also use here the parameterized query approach. 第三,在string命令中嵌入变量名称不会转换实际数字中的变量,您还应该使用参数化查询方法。

As an example: 举个例子:

private void button1_Click(object sender, EventArgs e)
{
    if (Convert.ToInt32(textBox1.Text) > 36)            
        MessageBox.Show("Insert a valid data");
    else
    {
        using(OleDbConnection cn = new OleDbConnection())
        using(OleDbCommand comm = new OleDbCommand("insert into ins_number (numb) values (?)", cn))
        {
             cn.Open();
             comm.Parameters.AddWithValue("@p1",Convert.ToInt32(this.textBox1.Text));
             comm.ExecuteNonQuery();
             da = new OleDbDataAdapter("select Number,[Red],[Black],[1_18],[19_36],[Even],[Odd],"+ 
                              "[1Column],[2Column],[3Column],[1Dozen],[2Dozen],[3Dozen] " +
                              "from [ins_number] where numb=? order by [Id_Numb] desc");
             da.SelectCommand.Parameters.AddWithValue("@p1", Convert.ToInt32(this.textBox1.Text));
             ds = new DataSet();
             da.Fill(ds);
             dataGridView1.DataSource = ds.Tables[0];        
        }
    }
}

I have moved the global connection variable inside the Click event and enclosed in a using statement. 我已经在Click事件中移动了全局连接变量并将其括在using语句中。 This will close and dispose the connection once used also in case of exceptions. 如果出现异常,这将关闭并处理一旦使用的连接。 Of course you should remove the global declaration, initialization and openinig in the form_load event. 当然,您应该在form_load事件中删除全局声明,初始化和openinig。

There are other errors in the query used to fill the datagrid but I cannot be sure what are your intentions here. 用于填充数据网格的查询中还有其他错误,但我无法确定您的意图是什么。 I have changed your query to retrieve the record just inserted, but if this is not your plan, then change appropriately the WHERE condition. 我已经更改了您的查询以检索刚插入的记录,但如果这不是您的计划,则适当更改WHERE条件。

Also, if you find an error in the input data, then I am sure that you don't want to execute the insert so an else part is needed after the messagebox display.... 此外,如果您在输入数据中发现错误,那么我确定您不想执行插入,因此在消息框显示后需要其他部分....

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM