[转帖]C#怎么更新MySQL的BLOB字段_MySQL, Oracle及数据库讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  MySQL, Oracle及数据库讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 3878 | 回复: 0   主题: [转帖]C#怎么更新MySQL的BLOB字段        下一篇 
大红薯
注册用户
等级:少校
经验:1440
发帖:159
精华:0
注册:2011-7-21
状态:离线
发送短消息息给大红薯 加好友    发送短消息息给大红薯 发消息
发表于: IP:您无权察看 2014-11-14 16:11:13 | [全部帖] [楼主帖] 楼主

C#如何更新MySQL的BLOB字段


我找到一些代码,但不好用,不懂C#,所以来这里请教大家了!

C# code
FileStream fs = null;
const string sConn = "server=(local);Initial
Catalog=Northwind;UID=ctester;PWD=password";
try {
      conn = new SqlConnection(sConn);
      cmd = new SqlCommand("UPDATE Categories SET Picture = ?Picture WHERE
      CategoryName = 'Seafood'", conn);
      fs = new FileStream("c:\\Builder.doc", FileMode.Open, FileAccess.Read);
      Byte[] blob = new Byte[fs.Length];
      fs.Read(blob, 0, blob.Length);
      fs.Close();
      param = new SqlParameter("Picture", SqlDbType.VarBinary, blob.Length,
      ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, blob);
      cmd.Parameters.Add(param);
      conn.Open();
      cmd.ExecuteNonQuery();
} catch (SqlException e){
      Console.Write("SQL Exception: " + e.Message());
} catch (Exception e) {
Console.Write("Exception: " e.Message());


实际上,就是如何将一个 byte[] 更新到mysql的BLOB上面,不是Insert 是 update 操作!

------解决方案--------------------
C# code
cmd = new SqlCommand("UPDATE Categories SET Picture =@Picture Picture WHERE
new SqlParameter("Picture", byte[])
------解决方案--------------------
SqlConnection conn =null;//连接字符串来用的
SqlCommand cmd = null; //执行SQL语句
SqlParameter param = null;//传参数来用的
FileStream fs = null;//文件流
const string sConn = "server=(local);Initial
Catalog=Northwind;UID=ctester;PWD=password";//SQL的连接字符串
try {
      conn = new SqlConnection(sConn);//实利化连接字符串
      cmd = new SqlCommand("UPDATE Categories SET Picture = ?Picture WHERE
      CategoryName = 'Seafood'", conn);//SQL语句
      fs = new FileStream("c:\\Builder.doc", FileMode.Open, FileAccess.Read);//用文件流读取c:\\Builder.doc
      Byte[] blob = new Byte[fs.Length];//一个Byte数组
      fs.Read(blob, 0, blob.Length);//读取文件流
      fs.Close();//关闭文件流
      param = new SqlParameter("Picture", SqlDbType.VarBinary, blob.Length,
      ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, blob);//传入的参数
      cmd.Parameters.Add(param);//添加到数据库里面
      conn.Open();//关闭数据库连接
      cmd.ExecuteNonQuery();//反回受影响行数
} catch (SqlException e){
      Console.Write("SQL Exception: " + e.Message());//异常
} catch (Exception e) {
      Console.Write("Exception: " e.Message());//异常
}
------解决方案--------------------
MySQL/MSSQL?


如果文件比较大的话,需要循环读取文件内容,。
MSSQL下面是:

UPDATETEXT { table_name.dest_column_name dest_text_ptr }
{ NULL | insert_offset }
{ NULL | delete_length }
[ WITH LOG ]
[ inserted_data
| { table_name.src_column_name src_text_ptr } ]


如果2005等较新的版本,用write 子 句的update.

USE AdventureWorks;
GO
DECLARE @MyTableVar table (
DocumentID int NOT NULL,
SummaryBefore nvarchar(max),
SummaryAfter nvarchar(max));
UPDATE Production.Document
SET DocumentSummary .WRITE (N'features',28,10)
OUTPUT INSERTED.DocumentID,
DELETED.DocumentSummary,
INSERTED.DocumentSummary
INTO @MyTableVar
WHERE DocumentID = 3 ;
SELECT DocumentID, SummaryBefore, SummaryAfter
FROM @MyTableVar;
GO
------解决方案--------------------


如果数据库是Mysql的话,连接不能用sqlconnection了,可能是oledbconnection类别,或者专门为Mysql开发的ADO.Net库。

------解决方案--------------------
C# code
OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["NEWOracleConn"].ToString());
OracleCommand cmd = new OracleCommand("UPDATE TUSER SET PHOTO=:photo WHERE userid=:id", conn);
Console.WriteLine(cmd.CommandText);
cmd.Parameters.Add("photo",OracleType.Blob);
cmd.Parameters["photo"].Value = photo;
cmd.Parameters.Add("id", OracleType.Number);
cmd.Parameters["id"].Value = id;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
------解决方案--------------------
MySql.Data.MySqlClient.MySqlCommand cmm = null;
cmm = new MySql.Data.MySqlClient.MySqlCommand("", connect);
MySql.Data.MySqlClient.MySqlParameter param = null;
param = new MySql.Data.MySqlClient.MySqlParameter("?Picture", System.Data.DbType.Binary);
param.Value = System.Text.Encoding.Default.GetBytes("");
cmm.Parameters.Add(param);
cmm.ExecuteNonQuery();
------解决方案--------------------


使用 SUN的 System.Data.MySqlClient 这个 数据接口调用的吧 
这个和 System.Data.SqlClient 什么都一样. 
估计 System.Data.MySqlClient 已经自动帮我们把byte[] 转换了
不过没试过.楼主好运

.
------解决方案--------------------


用MySQL的dll啊,很好用,很简单!!

http://dev.mysql.com/downloads/connector/net/6.1.html
------解决方案--------------------


我在C++CLI 中用过,和C#仅仅表现形式稍有差别,你很容易看懂。自己加上try catch
直接用OdbcConnection 用其它上层数据库连接类的也有,如果需要可以给你。

int UpdateBlob(OdbcConnection^ m_dbConn, String^ FileName,int docID)
{
      //you should put following code into try catch
      //support you have a table with 2 columns: docID and imgfile
      //read image file
      FileStream^ fs = gcnew FileStream(FileName, FileMode::Open, FileAccess::Read);
      int FileSize = (int)fs->Length;
      array<Byte>^ rawData = gcnew array<Byte>(FileSize);
      fs->Read(rawData, 0, FileSize);
      fs->Close();
      //make sql
String^ sql = String::Format("UPDATE table1 VALUES({0},?)",docID);
      OdbcCommand^ cmd = gcnew OdbcCommand(sql,m_dbConn);
      cmd->Parameters->Add("imgfile",OdbcType::Binary,FileSize,"imgfile")->Value = rawData;
      //do update now
      ret = cmd->ExecuteNonQuery();
      return ret;
}
------解决方案--------------------
http://blog.csdn.net/sciland/archive/2009/03/25/4023679.aspx


我以前在c#中连接过MySQL,上面的链接有介绍;像 string sql = "update table_name set col_name='" + values + "'where col2='" + values2 + "'";完成后就执行 RunSqlDatacmd(sql)就好了,RunSqlDatacmd(sql)代码如下:

public static long RunSqlDatacmd(string sql) //sql语句执行成员
{
      MySqlConnection dbconn = new MySqlConnection("Database='Online';Data Source='localhost';User Id='root';Password='123456';charset=utf8");
      MySqlCommand cmd = dbconn.CreateCommand();
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = sql;
      long ret = 0;
      try
      {
            if (cmd.Connection.State == ConnectionState.Broken)
            {
                  cmd.Connection.Close();
                  cmd.Connection.Open();
            }
            else if (cmd.Connection.State == ConnectionState.Closed)
            {
                  cmd.Connection.Open();
            }
            // else if (cmd.Connection.State == ConnectionState.Open)
            // {
                  ret = cmd.ExecuteNonQuery();
            // }
            //else
            // {
                  // ret = -102;
            // }
      }
      catch (Exception ex)
      {
            string m = ex.Message;
            ret = -5;
      }
      cmd.Dispose();
      dbconn.Close();
      return ret;
}
}
}


Linux下怎么解压Windows的exe文件
Linux下如何解压Windows的exe文件

我的OS是Ubuntu12.04, 昨天下载了wine,从舍友的电脑(Win7)上拷了魔兽争霸3, 在wine的注册表里面设置了War3 video 的width 和 height, 与屏幕的 W 和 H一样, 就实现全屏了, 运行起来一点都不卡, 还可以与舍友局域网对战玩DOTA,唯一美中不足的就是在启动器里没有war3的图标, 每次只能从点击运行war3的shell脚本, 不爽, 于是, find / -name "*.desktop" > desktop.txt , 然后照抄一份, 修改 Icon, Exec, 等选项的参数, 终于可以在启动器里点击图标开始war3了, 但我在网上找了半天, 找到的war3的图标没一个是与windows中的图标一样的, 很郁闷。 忽然记起, 以前用Ubuntu时, 下载过一些exe文件, 没事干, 就把它解压之后从中找图片,感觉很好玩。 可今天我解压war3.exe时, 出错了。 不知道Linux下有没有可以解压exe文件的工具?

------解决方案--------------------

lz,何必呢....

双系统才是正道.

------解决方案--------------------

。。。linux也可以玩魔兽争霸了?

------解决方案--------------------

额,这么强大,可是我的笔记本就装了个centos minimal当主机用。。。 好早之前也试过几次用桌面版linux,当时Linux还没现在认识深刻,让你这么一说我又有冲动了。

QT下编译的总是显示异常
QT下编译的总是显示错误?

我用的是QT的SDK 总是显示错误。

main.cpp : warning C4819: 该文件包含不能在当前代码页(936)中表示的字符。请将该文件保存为 Unicode 格式以防止数据丢失

F:\sm\mqapi\include\mqapi.h : warning C4819: 该文件包含不能在当前代码页(936)中表示的字符。请将该文件保存为 Unicode 格式以防止数据丢失

main.cpp(16) : warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.


  e:\Program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\stdio.h(234) : 参见“fopen”的声明

main.cpp(42) : warning C4996: 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.


  e:\Program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\stdio.h(371) : 参见“sprintf”的声明

  正在创建库 debug\test.lib 和对象 debug\test.exp

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: __thiscall QByteArray::~QByteArray(void)" (__imp_??1QByteArray@@QAE@XZ),该符号在函数 _WinMain@16 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "void __cdecl qWinMain(struct HINSTANCE__ *,struct HINSTANCE__ *,char *,int,int &,class QVector<char *> &)" (?qWinMain@@YAXPAUHINSTANCE__@@0PADHAAHAAV?$QVector@PAD@@@Z),该符号在函数 _WinMain@16 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: char * __thiscall QByteArray::data(void)" (__imp_?data@QByteArray@@QAEPADXZ),该符号在函数 _WinMain@16 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: __thiscall QString::~QString(void)" (__imp_??1QString@@QAE@XZ),该符号在函数 _WinMain@16 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: class QByteArray __thiscall QString::toLocal8Bit(void)const " (__imp_?toLocal8Bit@QString@@QBE?AVQByteArray@@XZ),该符号在函数 _WinMain@16 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: static class QString __cdecl QString::fromWCharArray(unsigned short const *,int)" (__imp_?fromWCharArray@QString@@SA?AV1@PBGH@Z),该符号在函数 _WinMain@16 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: bool __thiscall QBasicAtomicInt::deref(void)" (__imp_?deref@QBasicAtomicInt@@QAE_NXZ),该符号在函数 "public: __thiscall QVector<char *>::~QVector<char *>(void)" (??1?$QVector@PAD@@QAE@XZ) 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: bool __thiscall QBasicAtomicInt::operator!=(int)const " (__imp_??9QBasicAtomicInt@@QBE_NH@Z),该符号在函数 "public: void __thiscall QVector<char *>::detach(void)" (?detach@?$QVector@PAD@@QAEXXZ) 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) void * __cdecl qMemSet(void *,int,unsigned int)" (__imp_?qMemSet@@YAPAXPAXHI@Z),该符号在函数 "public: __thiscall QVector<char *>::QVector<char *>(int)" (??0?$QVector@PAD@@QAE@H@Z) 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: class QBasicAtomicInt & __thiscall QBasicAtomicInt::operator=(int)" (__imp_??4QBasicAtomicInt@@QAEAAV0@H@Z),该符号在函数 "public: __thiscall QVector<char *>::QVector<char *>(int)" (??0?$QVector@PAD@@QAE@H@Z) 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: static void __cdecl QVectorData::free(struct QVectorData *,int)" (__imp_?free@QVectorData@@SAXPAU1@H@Z),该符号在函数 "public: static void __cdecl QVectorTypedData<char *>::free(struct QVectorTypedData<char *> *,int)" (?free@?$QVectorTypedData@PAD@@SAXPAU1@H@Z) 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) void __cdecl qBadAlloc(void)" (__imp_?qBadAlloc@@YAXXZ),该符号在函数 "private: struct QVectorData * __thiscall QVector<char *>::malloc(int)" (?malloc@?$QVector@PAD@@AAEPAUQVectorData@@H@Z) 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: static struct QVectorData * __cdecl QVectorData::allocate(int,int)" (__imp_?allocate@QVectorData@@SAPAU1@HH@Z),该符号在函数 "private: struct QVectorData * __thiscall QVector<char *>::malloc(int)" (?malloc@?$QVector@PAD@@AAEPAUQVectorData@@H@Z) 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: static struct QVectorData * __cdecl QVectorData::reallocate(struct QVectorData *,int,int,int)" (__imp_?reallocate@QVectorData@@SAPAU1@PAU1@HHH@Z),该符号在函数 "private: void __thiscall QVector<char *>::realloc(int,int)" (?realloc@?$QVector@PAD@@AAEXHH@Z) 中被引用

qtmaind.lib(qtmain_win.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) void __cdecl qt_assert(char const *,char const *,int)" (__imp_?qt_assert@@YAXPBD0H@Z),该符号在函数 "private: void __thiscall QVector<char *>::realloc(int,int)" (?realloc@?$QVector@PAD@@AAEXHH@Z) 中被引用

debug\test.exe : fatal error LNK1120: 15 个无法解析的外部命令

cl -c -nologo -Zm200 -Zc:wchar_t- -Zi -MDd -GR -EHsc -W3 -w34100 -w34189 -DUNICODE -DWIN32 -DQT_LARGEFILE_SUPPORT -DQT_DLL -DQT_HAVE_MMX -DQT_HAVE_3DNOW -DQT_HAVE_SSE -DQT_HAVE_MMXEXT -DQT_HAVE_SSE2 -DQT_THREAD_SUPPORT -I"e:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include" -I"." -I".." -I"..\src" -I"..\include" -I"e:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\ActiveQt" -I"debug" -I"e:\QtSDK\Desktop\Qt\4.8.0\msvc2010\mkspecs\win32-msvc2010" -Fodebug\ @C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\main.obj.6000.63.jom
link /LIBPATH:"e:\QtSDK\Desktop\Qt\4.8.0\msvc2010\lib" /NOLOGO /DYNAMICBASE /NXCOMPAT /DEBUG /MANIFEST /MANIFESTFILE:"debug\test.intermediate.manifest" /SUBSYSTEM:WINDOWS "/MANIFESTDEPENDENCY:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*'" /OUT:debug\test.exe @C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\test.exe.6000.1157.jom
E:\QtSDK\QtCreator\bin\jom.exe -f Makefile.Debug
jom: F:\sm\mqapi\test\Makefile.Debug [debug\test.exe] Error 1120
------解决方案--------------------


简直了!

你是不是直接编译拿来的别人的工程呢

------解决方案--------------------

把所有中文注释全部删掉后试试看,那里面估计一大堆乱码吧

--转自 北京联动北方科技有限公司




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论