• 小白5分钟上手c#数据库操作(二) 基础的增删改查


    上一小节,我们已经准备好了一个数据库文件,现在我们先不用微软包装好的各种Entity Framework,

    自己用基础的方法对数据库进行增删改查。

    前期准备:

    新建一个console工程,把上一小节的数据库拷贝到工程目录下,copy local 设置成true,

    目录结构大致长这样:

     

    然后添加一个nuget包,方面后面使用各种c#提供的方法:

    基本上常用的操作里,查数据是一类,增删改是一类

    先看怎么查数据:

                // 查询数据
                using (var connection = new SQLiteConnection("data source=Student.db"))
                {
                    connection.Open();
                    var command = new SQLiteCommand("select * from StudentInformation", connection);
                    var adapter = new SQLiteDataAdapter(command);
                    var dataSet = new DataSet();
                    adapter.Fill(dataSet);
                    var table = dataSet.Tables[0];
                }
    

      

    效果展示:

    剩下的增删改,原理都一样,都是写sql语句,然后使用command上面的ExecuteNonQuery方法执行

    增加数据

                // 增加数据
                using (var connection = new SQLiteConnection("data source=Student.db"))
                {
                    connection.Open();
                    var command = new SQLiteCommand("insert into StudentInformation " +
                        "values("王五",22,"陕西省西安市长安区","看书,听音乐",3)", connection);
                    var result = command.ExecuteNonQuery();
                }
    

      

    效果:

    执行前:

    执行后:

    删除数据

                // 删除数据
                using (var connection = new SQLiteConnection("data source=Student.db"))
                {
                    connection.Open();
                    var command = new SQLiteCommand("delete from StudentInformation where Id = 2", connection);
                    var result = command.ExecuteNonQuery();
                }
    

      

    效果:

    执行前:

    执行后:

    修改数据

                // 修改数据
                using (var connection = new SQLiteConnection("data source=Student.db"))
                {
                    connection.Open();
                    var command = new SQLiteCommand("update StudentInformation set Name = '张三New' where Id = 2", 
                        connection);
                    var result = command.ExecuteNonQuery();
                }
    

      

    效果:

    执行前:

    执行后:

    到此为止,我们已经能通过c#提供的方法 使用sql语句,对数据库文件进行增删改查了。

  • 相关阅读:
    敏捷之旅--携程境外租车团队敏捷实践
    (一)LoadRunner安装
    性能测试,相关术语解析
    Newtonsoft.Json
    主流浏览器基于哪些内核?
    火狐浏览器与谷歌浏览器区别在哪里?
    带宽计算-大B与小b的区别
    loadrunner11录制不成功解决方法
    代码中的事务约束
    IOC框架Ninject实践总结
  • 原文地址:https://www.cnblogs.com/chenyingzuo/p/12099530.html
Copyright © 2020-2023  润新知