操作 SQLite 数据库进行图片存储

// 引用dll
// System.Data.dll
// System.Data.SQLite.dll using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.IO;
using System.Windows; namespace WpfAppSychronize
{
public partial class MainWindow : Window
{
string fileDirectory = AppDomain.CurrentDomain.BaseDirectory + "GuestImages\\";
public MainWindow()
{
InitializeComponent(); if (!Directory.Exists(fileDirectory))
{
Directory.CreateDirectory(fileDirectory);
}
} private void Button_Click(object sender, RoutedEventArgs e)
{
QueryImagesFromFile();
} /// <summary>
/// 读取图片文件列表
/// </summary>
/// <returns></returns>
public List<Guest> QueryImagesFromFile()
{
string diretory = fileDirectory;
string[] filePaths = Directory.GetFiles(diretory);
List<Guest> guests = new List<Guest>(); foreach (var path in filePaths)
{
int fileLength = ;
byte[] image = null;
using (FileStream fs = File.OpenRead(path))
{
fileLength = (int)fs.Length;
image = new byte[fileLength];
fs.Read(image, , fileLength);
} Guest guest = new Guest();
string fileName = path.Substring(path.LastIndexOf("\\") + );
fileName = fileName.Substring(, fileName.LastIndexOf("."));
long id = ;
long.TryParse(fileName, out id);
guest.GuestId = id;
guest.GuestImage = image;
guests.Add(guest);
}
return guests;
} /// <summary>
/// 从SQL Server数据库中读取图片字段信息
/// </summary>
/// <returns></returns>
public List<Guest> QueryImagesFromSQLDB()
{
string sql = @"SELECT [GuestID],[GuestImage] FROM [GuestInfo]";
List<Guest> guests = new List<Guest>(); using (SqlDataReader dr = DbHelperSQL.ExecuteReader(sql))
{
while (dr.Read())
{
Guest guest = new Guest();
guest.GuestId = Convert.ToInt64(dr["GuestID"]);
guest.GuestImage = dr["GuestImage"] != DBNull.Value ? (byte[])dr["GuestImage"] : null;
guests.Add(guest);
}
}
return guests;
} /// <summary>
/// 从SQLite数据库中读取图片字段信息
/// </summary>
/// <returns></returns>
public List<Guest> QueryImagesFromSQLiteDB()
{
DbHelperSQLite.connectionString = "Data Source=MyDatabase.sqlite;Version=3;"; string sql = @"SELECT [GuestID],[GuestImage] FROM [GuestInfo]";
List<Guest> guests = new List<Guest>(); using (SQLiteDataReader dr = DbHelperSQLite.ExecuteReader(sql))
{
while (dr.Read())
{
Guest guest = new Guest();
guest.GuestId = Convert.ToInt64(dr["GuestID"]);
guest.GuestImage = dr["GuestImage"] != DBNull.Value ? (byte[])dr["GuestImage"] : null;
guests.Add(guest);
}
}
return guests;
} /// <summary>
/// 把图片字节流保存为文件
/// </summary>
/// <param name="guests"></param>
public void SaveImagesToFile(List<Guest> guests)
{
foreach (var Guest in guests)
{
byte[] MyData = Guest.GuestImage;
string imagePath = fileDirectory + Guest.GuestId.ToString() + @".jpg"; using (FileStream fs = new FileStream(imagePath, FileMode.OpenOrCreate, FileAccess.Write))
{
fs.Write(MyData, , MyData.Length);
fs.Close();
}
}
} /// <summary>
/// 把图片字节流保存到SQL Server数据库
/// </summary>
/// <param name="guests"></param>
public void SaveImagesToSQLDB(List<Guest> guests)
{
foreach (var Guest in guests)
{
string sql = @"INSERT INTO [GuestInfo] ([GuestID],[GuestImage]) VALUES(@GuestID, @GuestImage)"; SqlParameter[] param = new SqlParameter[];
param[] = new SqlParameter("@GuestID", SqlDbType.BigInt);
param[].Value = Guest.GuestId;
param[] = new SqlParameter("@GuestImage", SqlDbType.Image);
param[].Value = Guest.GuestImage != null ? Guest.GuestImage : new byte[] { }; DbHelperSQL.ExecuteSql(sql, param);
}
} /// <summary>
/// 把图片字节流保存到SQLite数据库
/// </summary>
/// <param name="guests"></param>
public void SaveImagesToSQLiteDB(List<Guest> guests)
{
DbHelperSQLite.connectionString = "Data Source=MyDatabase.sqlite;Version=3;"; foreach (var Guest in guests)
{
string sql = @"INSERT INTO [GuestInfo]([GuestID],[GuestImage]) VALUES(@GuestID, @GuestImage)"; SQLiteParameter[] param = new SQLiteParameter[]; // 注意:这里赋值必须要用DbType.xxx,否则赋值不上
param[] = new SQLiteParameter("@GuestID", DbType.Int64);
param[].Value = Guest.GuestId;
param[] = new SQLiteParameter("@GuestImage", DbType.Binary);
param[].Value = Guest.GuestImage != null ? Guest.GuestImage : new byte[] { }; DbHelperSQLite.ExecuteSql(sql, param);
}
}
} public class Guest
{
public long GuestId { get; set; }
public byte[] GuestImage { get; set; }
} public abstract class DbHelperSQL
{
//数据库连接字符串
public static string connectionString = ""; /// <summary>
/// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string strSQL)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(strSQL, connection);
try
{
connection.Open();
SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
} /// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
}
}
} private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{ foreach (SqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
} public class DbHelperSQLite
{
//数据库连接字符串
public static string connectionString = ""; /// <summary>
/// 执行查询语句,返回SQLiteDataReader
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SQLiteDataReader</returns>
public static SQLiteDataReader ExecuteReader(string strSQL)
{
SQLiteConnection connection = new SQLiteConnection(connectionString);
SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
try
{
connection.Open();
SQLiteDataReader myReader = cmd.ExecuteReader();
return myReader;
}
catch (System.Data.SQLite.SQLiteException e)
{
throw new Exception(e.Message);
}
} /// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, params SQLiteParameter[] cmdParms)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SQLite.SQLiteException E)
{
throw new Exception(E.Message);
}
}
}
} private static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SQLiteParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
}
}

批量保存图片到数据库:

using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms; namespace DataImport
{
public partial class Form1 : Form
{
public List<string> _photoFilePathList = new List<string>();
string _connStr = "Data Source=192.168.10.109;Initial Catalog=HT_ACCESS;User ID=sa;Password=123456"; public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
GetFiles(textBox1.Text); int i = ;
foreach (var file in _photoFilePathList)
{
string err = "";
try
{
FileStream fs = new FileStream(file, System.IO.FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fs); byte[] imgData = binaryReader.ReadBytes((int)fs.Length); VIEW_M_PHOTO photo = new VIEW_M_PHOTO();
photo.EMPLOYEENO = "" + i.ToString();
photo.PHOTO = imgData;
photo.FILEEXT = "" + i.ToString(); //保存照片
AddPhoto(photo); i++;
}
catch (Exception ex)
{
err = ex.Message.ToString();
continue;
}
}
} public bool AddPhoto(VIEW_M_PHOTO model)
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
SqlCommand command = new SqlCommand(@"INSERT INTO [HT_ACCESS].[dbo].[HT_PHOTO] (EMP_NO,PHOTO_CONTENT,RECORD_COUNTER)
Values(@EMP_NO, @PHOTO_CONTENT, @RECORD_COUNTER)", connection); command.Parameters.Add("@EMP_NO",
SqlDbType.NVarChar, ).Value = model.EMPLOYEENO;
command.Parameters.Add("@PHOTO_CONTENT",
SqlDbType.Image, model.PHOTO.Length).Value = model.PHOTO;
command.Parameters.Add("@RECORD_COUNTER",
SqlDbType.NVarChar, ).Value = model.FILEEXT; connection.Open();
int rows = command.ExecuteNonQuery(); if (rows > )
{
return true;
}
else
{
return false;
}
}
}
private void btnOpenDirectory_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "请选择文件路径";
if (dialog.ShowDialog() == DialogResult.OK)
{
string foldPath = dialog.SelectedPath;
textBox1.Text = foldPath;
}
} public void GetFiles(string str)
{
DirectoryInfo parentFolder = new DirectoryInfo(str); //删除子文件夹
DirectoryInfo[] childFolders = parentFolder.GetDirectories();
foreach (DirectoryInfo dir in childFolders)
{
try
{
string dirName = dir.Name;
//if (dirName.Contains("obj") || dirName.Contains("bin"))
//{
// Directory.Delete(dir.FullName, true);
//}
}
catch (Exception ex)
{
throw ex;
}
} //删除当前文件夹内文件
FileInfo[] files = parentFolder.GetFiles();
foreach (FileInfo file in files)
{
//string fileName = file.FullName.Substring((file.FullName.LastIndexOf("\\") + 1), file.FullName.Length - file.FullName.LastIndexOf("\\") - 1);
string fileName = file.Name;
try
{
//if (fileName.Contains("cs"))
//{
// //File.Delete(file.FullName);
// string path = file.FullName;
// //Path.ChangeExtension(path, "txt");
// File.Move(path, Path.ChangeExtension(path, "txt"));
//} _photoFilePathList.Add(file.FullName);
}
catch (Exception ex)
{
throw ex;
}
} //递归搜索子文件夹内文件
foreach (DirectoryInfo childFolder in parentFolder.GetDirectories())
{
GetFiles(childFolder.FullName);
}
}
}
}

C# 自动批量导入图片到数据库中的更多相关文章

  1. [转]iOS:批量导入图片和视频到模拟器的相册

    IOS开发中我们经常会用到模拟器调试,模拟器有个主要的好处就是程序启动块,最重要的是如果没有证书的话,我们就只能在模拟器上调试了.使用模拟器调试时我们可能碰到需要从系统相册选择图片的情况,特别是做图片 ...

  2. mysql中把一个表的数据批量导入另一个表中

    mysql中把一个表的数据批量导入另一个表中   不管是在网站开发还是在应用程序开发中,我们经常会碰到需要将MySQL或MS SQLServer某个表的数据批量导入到另一个表的情况,甚至有时还需要指定 ...

  3. 如何将dmp文件导入到oracle数据库中

    如何将dmp文件导入到oracle数据库中 1.首先,我们可以先建立自己的一个用户表空间,创建表空间的格式如下: CREATE TABLESPACE certification(表空间的名字) DAT ...

  4. 怎样把excel的数据导入到sqlserver2000数据库中

    在做程序的时候有时需要把excel数据导入到sqlserver2000中,以前没从外部导入过数据,今天刚做了一下导入数据,感觉还是蛮简单的,没做过之前还想着多么的复杂呢,下面就来分享一下我是如何把ex ...

  5. 用ttBulkCp把excel中的数据导入到timesten数据库中

    最近要做数据预处理,需要用到数据库.而且是以前从来没听说过的TimesTen. 首要目标是要把Excel里的数据,导入到TimesTen数据库中.而TimesTen在win10里用不了,于是我就在虚拟 ...

  6. 如何简单地利用Bitmap为中介储存图片到数据库中

        这是我的第一篇博文,请大家多多指教!     大概一个月之前,在跟朋友合作开发一个APP的过程中,我们发现到一个问题:图片的存储.因为数据库没有图片这种数据类型,当用户上传的图片需要存储的时候 ...

  7. 023医疗项目-模块二:药品目录的导入导出-从数据库中查出数据用XSSF导出excel并存放在虚拟目录最后下载(包括调试)

    我们要实现的效果:     进入到这个页面后,输入要查询的条件,查询出药品表的数据,然后按下导出按钮 ,就会在服务器的一个目录下生成一个药品表的excel表格.  点击"导出"之后 ...

  8. EXCEL批量导入到Sqlserver数据库并进行两表间数据的批量修改

    Excel 大量数据导入到sqlserver生成临时表并将临时表某字段的数据批量更新的原表中的某个字段 1:首先要对EXCEL进行处理 列名改成英文,不要有多余的列和行(通过ctrl+shift 左或 ...

  9. C#中实现excel文件批量导入access数据表中

    一 .界面简单设计如下: 二 .代码如下: using System; using System.Collections.Generic; using System.ComponentModel; u ...

随机推荐

  1. redis运维相关(基本数据库命令)【十四】

    -----------------------------运维相关------------------------- redis持久化,两种方式1.rdb快照方式2.aof日志方式 --------- ...

  2. 2017年12月14日 一个Java开发的Python之路----------------(二)

    说一个收获最大的,就是这个关闭流对象 之前写java读取文件的时候,最后往往要关闭流对象,以前我一直不明白,为什么,我不使用.close()方法,文件也可以读取成功,总感觉没有什么意义 原来是因为,这 ...

  3. ***CodeIgnite/CI 去掉 index.php的 配置

    CI有效删除URL中的index.php 参考: http://codeigniter.org.cn/forums/thread-15444-1-1.html 读CI的使用手册的话,关于如何有效删除U ...

  4. MongoDB小结12 - update【多文档更新】

    当一次更新一个文档无法满足我们的脚步时,我们可以选择一次更新多个文档,及在update的第四个参数的位置添上true,及做多文档更新,建议就算不做多文档更新也显式的在第四个参数上置false,这样明确 ...

  5. 模拟用户点击弹出新页面不会被浏览器拦截_javascript技巧

    原文:http://www.html5cn.com.cn/article/zxzx/3195.html 相信用过window.open的小伙伴们都遇到过被浏览器拦截导致页面无法弹出的情况:我们换下思路 ...

  6. dubbo安装和使用

    转载:http://blog.csdn.net/zjcjava/article/details/78766095 背景 Dubbo的开源人梁飞在内部的交流会上宣布重启dubbo的维护和更新,具体PPT ...

  7. CF # 369 D2 D、E

    D,只要抓住每个点只有一个出度,那么图就能分成几个部分,而且可以发现,一个部分最多一个环. #include <iostream> #include <cstdio> #inc ...

  8. SQLServer时间分段查询

    统计连续时间段数据 if OBJECT_ID(N'Test',N'U') is not null drop table Test go create table Test( pscode decima ...

  9. 二分lower_bound()与upper_bound()的运用

    <span style="color:#6633ff;">/* G - 二分 Time Limit:2000MS Memory Limit:32768KB 64bit ...

  10. CSP 201612-3 权限查询 【模拟+STL】

    201612-3 试题名称: 权限查询 时间限制: 1.0s 内存限制: 256.0MB 问题描述: 问题描述 授权 (authorization) 是各类业务系统不可缺少的组成部分,系统用户通过授权 ...