C#实现增删改查以及通过导入.xls读取数据

C#增删改查是最基本的功能,但是也容易出小问题。在这里博主提供一个可运行的源码,作为笔记的同时也希望能给予大家帮助。除此以外,还将分享一个通过导入.xls读取数据的源码。

  1. db.cs
    首先,我们创建一个db.cs类。
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace PressureSketch
{
    class db
    {
        public static string connectionstring = "server=localhost;database=XXX;uid=sa;pwd=111";

        public static SqlConnection OpenDB()
        {
            try
            {
                SqlConnection oConn = new SqlConnection(connectionstring);
                oConn.Open();

                return oConn;
            }
            catch
            {
                throw;
            }
        }

        public static void CloseDB(SqlConnection oConn)
        {
            try
            {
                oConn.Close();
            }
            catch
            {
                throw;
            }
        }

        public static DataSet Execute(string strCommandString)
        {
            try
            {
                SqlConnection oConn = OpenDB();

                DataSet oDataSet = new DataSet();
                SqlDataAdapter oDataAdapter = new SqlDataAdapter(strCommandString, oConn);
                oDataAdapter.Fill(oDataSet);

                CloseDB(oConn);

                return oDataSet;
            }
            catch
            {
                throw;
            }
        }

        public static int ExecuteNonQuery(string strCommandString)
        {
            int li_count = 0;
            SqlConnection oConn = null;
            SqlCommand oComm = null;
            try
            {
                oConn = new SqlConnection(connectionstring);
                oComm = new SqlCommand();
                oConn.Open();
                oComm.Connection = oConn;
                oComm.CommandText = strCommandString;
                li_count = oComm.ExecuteNonQuery();
                return li_count;
            }
            catch
            {
                return 0;
            }
            finally
            {
                if (oConn != null) oConn.Close();
            }
        }

        public static int ExecuteReid(string strCommandString)
        {
            int li_count = 0;
            SqlConnection oConn = null;
            SqlCommand oComm = null;
            try
            {
                oConn = new SqlConnection(connectionstring);
                oComm = new SqlCommand();
                oConn.Open();
                oComm.Connection = oConn;
                oComm.CommandText = strCommandString;
                li_count = Convert.ToInt32(oComm.ExecuteScalar().ToString());
                return li_count;
            }
            catch
            {
                return 0;
            }
            finally
            {
                if (oConn != null) oConn.Close();
            }
        }

    }
}

  1. 将已有数据通过表格形式显示出来
        private int get_db1(string as_where)
        {
            string ls_sql = "select time,p4far1 from table_test " + as_where + " order by dbid";
            DataSet ds = new DataSet();
            try
            {
                ds = db.Execute(ls_sql);
            }
            catch
            {
                //数据库出错,相应的sql为getsql()
                MessageBox.Show("error of connect database");
            }
            dataGridView1.DataSource = ds.Tables[0].DefaultView;

            dataGridView1.Columns[0].HeaderText = "时间(min)";
            dataGridView1.Columns[1].HeaderText = "P4";

            dataGridView1.Columns[0].Width = 150;
            dataGridView1.Columns[1].Width = 150;
            dataGridView1.Columns[2].Visible = false;

            return ds.Tables[0].Rows.Count;

        }

效果图

  1. 增、改数据
        private void bt_save_Click(object sender, EventArgs e)
        {
            if (ls_dbid == "")
            {
                string ls_sql = "INSERT INTO table_test ( time,p4far1 )  VALUES (  @@time, @@p4far1 ); SELECT dbid FROM table_test WHERE (dbid = @@IDENTITY)";
                //ls_sql = ls_sql.Replace("@@dbid", "'" + textBox4.Text.ToString() + "'");                 
                ls_sql = ls_sql.Replace("@@time", "'" + textBox2.Text.ToString() + "'");
                ls_sql = ls_sql.Replace("@@p4far1", "'" + textBox3.Text.ToString() + "'");
                int li_ret1 = db.ExecuteReid(ls_sql);
                if (li_ret1 > 0)
                {
                    ls_dbid = li_ret1.ToString();
                }
                else
                {
                    MessageBox.Show("增加失败", "信息");
                    return;
                }
            }
            else
            {
                string ls_sql = "update table_test set time=@@time,p4far1=@@p4far1 where dbid = " + ls_dbid;      
                ls_sql = ls_sql.Replace("@@time", "'" + textBox2.Text.ToString() + "'");
                ls_sql = ls_sql.Replace("@@p4far1", "'" + textBox3.Text.ToString() + "'");
                db.ExecuteNonQuery(ls_sql);
            }
            get_db1("");
            MessageBox.Show("保存成功!", "信息");
        }


  1. 删除数据
        private void bt_del_Click(object sender, EventArgs e)
        {
            if (ls_dbid == "")
            {
                MessageBox.Show("请选择要删除的记录");
            }
            else
            {
                string ls_sql = "delete from table_test where dbid=" + ls_dbid;
                db.ExecuteNonQuery(ls_sql);
                get_db1("");
                MessageBox.Show("删除成功!", "信息");
            }
        }

  1. 查询数据
        private void txt_cx_TextChanged(object sender, EventArgs e)
        {
            string ls_where = "";
            if (this.Text.Equals(""))
            {
                ls_where = "";
            }
            else
            {
                ls_where = " where (time like '%" + textBox1.Text.ToString() + "%')";
                //ls_where = " where (time like '%" + textBox1.Text.ToString() + "%') or (xm2 like '%" + textBox1.Text.ToString() + "%') or (xm3 like '%" + textBox1.Text.ToString() + "%')";
            }
            get_db1(ls_where);
        }

  1. 左击数据进行填充
        private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            textBox2.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
            textBox3.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
            ls_dbid = dataGridView1.CurrentRow.Cells[21].Value.ToString();
        }

  1. 导入.xls读取数据
        private DataSet xsldata(string filepath)
        {

            string strCon = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;IMEX=1'";

            System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strCon);

            string strCom = "SELECT * FROM [Sheet1$]";

            Conn.Open();

            System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn);

            DataSet ds = new DataSet();

            myCommand.Fill(ds, "[Sheet1$]");
            dataGridView1.DataSource = ds.Tables[0];
            Conn.Close();

            return ds;

        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (textBox25.Text == "")
            {
                MessageBox.Show("请选择要导入的Excel文档!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;

            }
            string filepath = textBox25.Text;
            SqlConnection conn = new SqlConnection(strcon);//链接数据库

            conn.Open();

            try
            {



                DataSet ds = new DataSet();

                //取得数据集
                //调用上面的函数

                ds = xsldata(filepath);
                //dataGridView2.DataSource = ds.Tables[0];
                int errorcount = 0;//记录错误信息条数

                int insertcount = 0;//记录插入成功条数

                int updatecount = 0;//记录更新信息条数

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    int time = Convert.ToInt32(ds.Tables[0].Rows[i][0].ToString());
                    double p4far1 = Convert.ToDouble(ds.Tables[0].Rows[i][1].ToString());
                    double p1mid1 = Convert.ToDouble(ds.Tables[0].Rows[i][2].ToString());
                    if (time.ToString() != "")
                    {
                        SqlCommand selectcmd = new SqlCommand("select count(*) from table_test where time=" + time, conn);
                        int count = Convert.ToInt32(selectcmd.ExecuteScalar());
                        if (count > 0)
                        {
                            updatecount++;

                        }
                        else
                        {

                            SqlCommand insertcmd = new SqlCommand("insert into table_test(time,p4far1) values(" + time + ",'" +

                                                                  p4far1  + ")", conn);

                            insertcmd.ExecuteNonQuery();

                            insertcount++;

                        }



                    }
                    else
                    {

                        //MessageBox.Show("电子表格信息有错!");
                        errorcount++;
                        ;

                    }

                }

                MessageBox.Show(insertcount + "条数据导入成功!" + updatecount + "条数据重复!" + errorcount + "条数据部分信息为空没有导入!");

            }

            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);

            }

            finally
            {
                conn.Close();

            } 

        }

需要注意的是:string strCon = “Provider=Microsoft.Ace.OleDb.12.0;Data Source=” + filepath + “;Extended Properties=‘Excel 8.0;IMEX=1’”;这里和office版本有关,注意修改。

  1. 在表格前添加序号
    注意红圈
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {

            DataGridView dgv = sender as DataGridView;
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                                                e.RowBounds.Location.Y,
                                                dgv.RowHeadersWidth - 4,
                                                e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                                  dgv.RowHeadersDefaultCellStyle.Font,
                                  rectangle,
                                  dgv.RowHeadersDefaultCellStyle.ForeColor,
                                  TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

  1. 运行
    最终在构造函数中调用get_db1("");即可,其中 public static string strcon = “server=localhost;database=XXX;uid=sa;pwd=111”; private string ls_dbid = “”;
  2. 数据库设计
    数据库设计
    列属性
  3. .xls格式
    .xls格式
    通过.xls读取数据需注意格式,即首行字段名。

以上就是C#实现增删改查以及通过.xls读取数据的相关代码,欢迎各位交流以及指导!

向IT工作者致敬,后丹之喜碧CatBrother欢迎吐槽:
后丹-喜碧CatBrother

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值