非专业.net开发,突然接手一个老旧的.net系统,要添加一个将图片上传至ORACLE数据库新功能,磕磕绊绊撸了一波代码,纯面向百度编程,完成需求。
private void uploda_Click(object sender, EventArgs e)
{
try
{
string bDCDYID = this.infoTJ.BDCDYID;
//先将图片保存到本地
if (!this.m_mapLayoutControl.MapLayout.PrintToFile(Application.StartupPath + "//" + bDCDYID + ".png", PrintFileType.PNG, 400))
{
Msg.Information("保存失败!");
}
else
{ //获取文件流
FileStream stream = new FileStream(Application.StartupPath + "//" + bDCDYID + ".png", FileMode.Open, FileAccess.Read);
//将文件读取到byte数组
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
if (buffer != null)
{
string str2;
//删除原图片
File.Delete(Application.StartupPath + "//" + bDCDYID + ".png");
//调用数据库操作
if (this.UpdateItem(buffer, bDCDYID, out str2) != 0)
{
Msg.Information("导出成功!");
}
else
{
Msg.Information("导出失败" + str2);
}
}
}
}
catch
{
}
}
private int UpdateItem(byte[] photo, string bdcdyid, out string err)
{
int num;
err = null;
//打开数据库连接
OracleConnection connection = new OracleConnection(ConfigurationManager.ConnectionStrings["DataSource"].ConnectionString);
try
{
connection.Open();
OracleCommand command = new OracleCommand();
OracleCommand command2 = new OracleCommand();
command.Connection = connection;
command2.Connection = connection;
command.CommandText = "select BDCDYID from BDCS_ZDT where BDCDYID = :BDID";
OracleParameter parameter = new OracleParameter(":BDID", OracleType.VarChar)
{
Value = bdcdyid
};
command.Parameters.Add(parameter);
//执行查询,如果有数据则做更新操作,无数据则做新增操作
if (command.ExecuteScalar() == null)
{
command2.CommandText = "insert into BDCS_ZDT(BDCDYID,SCSJ,ZDT) values(:ID,:TIME,:PHOTO)";
OracleParameter parameter2 = new OracleParameter(":ID", OracleType.VarChar)
{
Value = bdcdyid
};
command2.Parameters.Add(parameter2);
parameter2 = new OracleParameter(":TIME", OracleType.DateTime)
{
Value = DateTime.Now
};
command2.Parameters.Add(parameter2);
parameter2 = new OracleParameter(":PHOTO", OracleType.Blob)
{
Value = photo
};
command2.Parameters.Add(parameter2);
num = command2.ExecuteNonQuery();
}
else
{
command2.CommandText = "update BDCS_ZDT set ZDT=:PHOTO,SCSJ=:TIME where BDCDYID = :ID";
OracleParameter parameter3 = new OracleParameter(":PHOTO", OracleType.Blob)
{
Value = photo
};
command2.Parameters.Add(parameter3);
parameter3 = new OracleParameter(":TIME", OracleType.DateTime)
{
Value = DateTime.Now
};
command2.Parameters.Add(parameter3);
parameter3 = new OracleParameter(":ID", OracleType.VarChar)
{
Value = bdcdyid
};
command2.Parameters.Add(parameter3);
num = command2.ExecuteNonQuery();
}
}
catch (Exception exception)
{
err = exception.Message;
num = 0;
}
finally
{
connection.Close();
}
return num;
}