Untiy实现向SQLite中插入Assets中某个目录下的所有文件名。

需求:向数据库中添加某个目录下所有的图片名。


1.数据库类

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


using Mono.Data.Sqlite;
using UnityEngine.SceneManagement;
using System.IO;


public class UserSql : MonoBehaviour
{

    public static UserSql Instance;
    SqliteConnection mySql;

    public void Awake()
    {
        Instance = this;


        // 路径
        string path = "Data Source=" + Application.streamingAssetsPath + "/MmorpgDataDemo.db";

        mySql = new SqliteConnection(path);

        // 尝试打开 错误关闭
        try
        {
            mySql.Open();
            Debug.Log("打开数据库===");
        }
        catch (System.Exception e)
        {
            mySql.Close();
        }



    }


    /// <summary>
    /// 最后关闭数据库
    /// </summary>
    private void OnDestroy()
    {
        mySql.Close();
    }


    /// <summary>
    /// 执行 sql 语句
    /// </summary>
    /// <param name="sql">填入sql语句</param>
    /// <returns></returns>
    public SqliteDataReader ExcuteOrder(string sql)
    {
        // 创建命令行
        SqliteCommand myCommond = mySql.CreateCommand();
        // 编辑命令
        myCommond.CommandText = sql;
        // 执行
        return myCommond.ExecuteReader();

    }




    /// <summary>
    /// 插入数据
    /// </summary>
    /// <param name="name">物品名</param>
    /// <param name="type">物品类型</param>
    /// <param name="imagePath">文件路径</param>
    /// <param name="contain">文件名包含</param>
    public void Insert(string name, string type, string imagePath, string contain)
    {

        if (Directory.Exists(imagePath))
        {
            DirectoryInfo direction = new DirectoryInfo(imagePath);
            FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
            for (int i = 0; i < files.Length; i++)
            {
                if (files[i].Name.Contains(contain) && files[i].Name.EndsWith(".png"))
                {
                    string sql = string.Format(" insert into Bag ( Name, Type, ImagePath ) values ( '{0}', '{1}', '{2}' ); ", name+i, type, files[i].Name);
                    ExcuteOrder(sql);
                    Debug.Log("Name : " + files[i].Name);
                }
            }
        }
    }
}

2.应用

public class PackageBack : MonoBehaviour
{
    void Start()
    {
        // 路径
        string imagePath = "C:/A/Unity/Project/DemoMMORPG/Assets/Resources/Boots";
        UserSql.Instance.Insert("Boots", "Boots", imagePath, "Boots");
    }
}

结果

 结果中 Name 结尾 0, 2, 4......是因为有 .meta 文件在数组中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值