zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#数据库编程(建立数据库表,数据库的连接,实现的源代码)

c#数据库连接编程 实现 建立 源代码
2023-09-14 09:16:33 时间

1.建立工程User1ADO

2.用access2003(也可以使用SQLServer2005 2008 )建立数据库表User1,表名为User1,字段一:ID号,字段二:用户名


3.把建立好的数据库表放在\User1ADO\bin\Debug下

4.在工程内写入代码:using System.Data.OleDb;//使用数据库

5.实现功能如下(加完整代码)


建立数据库连接

  private void button1_Click(object sender, EventArgs e)
        {
            string Afile = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=User1.mdb";
            AconnStr = new OleDbConnection(Afile);//设定数据库连接
            MessageBox.Show("数据库连接成功!");
        }

检索数据

private void button2_Click(object sender, EventArgs e)
        {
            AconnStr.Open();
            OleDbCommand Acmd = new OleDbCommand("select  * from User1 order by ID号;",AconnStr);
            OleDbDataReader odr = null;
            try
            {
                odr = Acmd.ExecuteReader();//执行获取命令
            }
            catch (System.Exception ex)
            {
                if (ex != null) MessageBox.Show("执行出错");
            }
            if (odr != null)
                listBox1.Items.Add("ID号\t\t用户名");//将两项加入listBox1
            while (odr.Read())
            {
                string TotalInfo = "";
                TotalInfo += odr["ID号"].ToString() + "\t";
                TotalInfo += odr["用户名"].ToString() + "\t";
                listBox1.Items.Add(TotalInfo + "\n");
            }
            odr.Close();//关闭数据流
            AconnStr.Close();//关闭数据连接
        }

插入数据

private void button3_Click(object sender, EventArgs e)
        {
            OleDbCommand Icmd = new OleDbCommand("Insert into User1(ID号,用户名) values('" + textBox1.Text + "','" + textBox2.Text + "');", AconnStr);
            AconnStr.Open();
            try
            {
                Icmd.ExecuteNonQuery();//执行插入操作
                MessageBox.Show("插入成功");
            }
            catch (System.Exception ex)
            {
                if (ex != null)
                    MessageBox.Show("插入操作出错!");
            }
          
            AconnStr.Close();
            
        }

删除数据

 private void button4_Click(object sender, EventArgs e)
        {
            OleDbCommand Dcmd = new OleDbCommand("delete from User1 where ID号='"+textBox1.Text+"';",AconnStr);
            AconnStr.Open();
            Dcmd.ExecuteNonQuery();//执行删除操作
            MessageBox.Show("删除成功");
            AconnStr.Close();


        }

修改数据

private void button5_Click(object sender, EventArgs e)
        {


       OleDbCommand Mcmd = new OleDbCommand("Update * from User where ID号='"+textBox1.Text+"' and 用户名='"+textBox2.Text+"';",AconnStr);
        
       }

刷新数据

 private void button6_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            this.button2_Click(sender, e);
        }