Sqlserver--like参数加百分号

 Sqlserver--like参数加%

 string sql = "select hr_key , user_id,user_name from  hruser where user_id like @userid " ;
        
        SqlConnection Sqlcon = new SqlConnection(ConfigurationManager.AppSettings["prConnection"]);
        SqlCommand sqlComm = new SqlCommand(sql, Sqlcon);

       // sqlComm.Parameters.Add("@userid", SqlDbType.VarChar);//添加参数
       // sqlComm.Parameters.Add(new SqlParameter("@userid", string.Format("{0}%", tbUserId.Text)));
        sqlComm.Parameters.Add(new SqlParameter("@userid", string.Format("{0}%", tbUserId.Text)));
        
        //sqlComm.Parameters["@userid"].Value = tbUserId.Text ;//为参数赋值
        Sqlcon.Open();
       // sqlComm.ExecuteNonQuery();
        //Sqlcon.Close();
        SqlDataReader Dreader = sqlComm.ExecuteReader();

       
        gvHrUser.DataSource = Dreader; 
        gvHrUser.DataBind();

        Sqlcon.Close();
       

posted @ 2012-03-09 21:18 青蛙學堂 阅读(2159) | 评论 (0)编辑 收藏

C#--sql实例

 

sql用法总结:

1.查询语句adpter里写sql,执行后把结果赋值给新建的dataset 对象ds,即可在gridview显示。  

SqlConnection con = new SqlConnection("server=ZMQHBD2007;database=data;uid=sa;pwd=123;");
                  //
上面这句等价于:
                 //private static string constring="”;
       con.Open();
       SqlDataAdapter sda = new SqlDataAdapter("select * from category", con);
                  //
上面这句等价于:
                  //string cmd= "select * from category";
                  // SqlDataAdapter sda = new SqlDataAdapter(cmd,con);
       DataSet ds = new DataSet();
       sda.Fill(ds, "category");
                 //
下面这5个语句等价
                 //this.GridView1.DataSource = ds;
                 //this.GridView1.DataSource = ds.Tables[0];
                 //this.GridView1.DataSource = ds.Tables["customers"];
                 //this.GridView1.DataSource = ds.Tables[0].DefaultView;
        this.GridView1.DataSource = ds.Tables["category"].DefaultView;
        this.GridView1.DataBind();
        con.Close();

注:利用SqlConnectionSqlDataAdapterDataSet实现表内容在GridView中显示。

  

2.sqlcommand执行sql,然后赋值给adaptercommand方法, adapter再填充数据给新建dataset对象的ds,然后显示

       SqlConnection con = new SqlConnection(…);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from category", con);
        SqlDataAdapter sda = new SqlDataAdapter();
        sda.SelectCommand = cmd;
         //
第三句话和第五句话可写为:
           //sda.SelectCommand = new SqlCommand("select * from category", con);
        DataSet ds = new DataSet();
        sda.Fill(ds, "category");
        this.GridView1.DataSource = ds.Tables["category"].DefaultView;
        this.GridView1.DataBind();
        con.Close();

利用SqlConnectionSqlCommandSqlDataAdapterDataSet实现表内容在GridView中显示。

        ////我最经常用这一种,同时连接对象是整个程序的公共对象,所以我一般会把数据库连接封装到一个类中,这样就可以在程序的任何地方随时调用

 

 

3.sqlcommand执行sql,然后执行reader属性,赋值给datareader对象,reader对象作为ds.


    SqlConnection con = new SqlConnection("…..");            //
双引号中的最后一个分号可以去掉
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from category", con);
           //
上面这句可写为:
           //SqlCommand cmd = new SqlCommand();
           //cmd.CommandText = "select * from category";
           //cmd.Connection = con;
           //cmd.CommandType = CommandType.Text; //
这条语句是多余的,因为默认就是Text
    
        SqlDataReader sdr = cmd.ExecuteReader();
        this.GridView1.DataSource = sdr;
        this.GridView1.DataBind();
        sdr.Close();
        con.Close();

利用SqlConnectionSqlCommandSqlDataReader实现表内容在GridView中显示。

 

注:加参数

SqlCommand sqlComm = new SqlCommand(sql, Sqlcon);

        sqlComm.Parameters.Add("@userid", SqlDbType.Int);//添加参数

        sqlComm.Parameters["@userid"].Value = Convert.ToInt32( tbUserId.Text) ;//为参数赋值

       

 

 

 

4.其他更新语句   
//
如果SQL语句是DeleteUpdateInsert  
SqlComman   cmd=new   SqlCommand();  
cmd.CommandText=SQL
语句;  
cmd.CommandType=System.Data.CommandType.Text;  
cmd.Connection=mycon;  
cmd.ExcuteNoQuery();  
   
mycon.Close();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2012-03-09 20:06 青蛙學堂 阅读(556) | 评论 (0)编辑 收藏

sql 2005中real,float,decimal的区别




decimal 数据类型最多可存储 38 个数字,所有数字都能够放到小数点的右边。decimal 数据类型存储了一个准确(精确)的数字表达法;不存储值的近似值。

定义 decimal 的列、变量和参数的两种特性如下: 

•          p   小数点左边和右边数字之和,不包括小数点。如 123.45,则 p=5,s=2。 

指定精度或对象能够控制的数字个数。

•          s 

指定可放到小数点右边的小数位数或数字个数。

p 和 s 必须遵守以下规则:0 <= s <= p <= 38。

numeric 和 decimal 数据类型的默认最大精度值是 38。在 Transact-SQL 中,numeric 与 decimal 数据类型在功能上等效。

当数据值一定要按照指定精确存储时,可以用带有小数的 decimal 数据类型来存储数字。

float 和 real 数据

float 和 real 数据类型被称为近似的数据类型。在近似数字数据类型方面,float 和 real 数据的使用遵循 IEEE 754 标准。

近似数字数据类型并不存储为多数数字指定的精确值,它们只储存这些值的最近似值。在很多应用程序中,指定值与存储值之间的微小差异并不明显。但有时这些差异也值得引起注意。由于 float 和 real 数据类型的这种近似性,当要求精确的数字状态时,比如在财务应用程序中,在那些需要舍入的操作中,或在等值核对的操作中,就不使用这些数据类型。这时就要用 integer、decimal、money 或 smallmone 数据类型。

在 WHERE 子句搜索条件中(特别是 = 和 <> 运算符),应避免使用 float 或 real 列。最好限制使用 float 和 real 列做 > 或 < 的比较。

IEEE 754 规格提供了四种舍入模式:舍入到最接近的值、上舍入、下舍入和舍入到零。Microsoft® SQL Server™ 使用上舍入。所有的数值必须精确到确定的精度,但会产生细小的浮点值变化。因为浮点数字的二进制表示法可以采用很多合法舍入规则中的任意一条,因此我们不可能可靠地量化一个浮点值。

转换 decimal 和 numeric 数据

对于 decimal 和 numeric 数据类型,Microsoft® SQL Server™ 将精度和小数位数的每个特定组合看作是不同的数据类型。例如,decimal(5,5) 和 decimal(5,0) 被当作不同的数据类型。(因此在编存储过程当中使用的变量采用Real 或 Float,而不采用decimal类型)

在 Transact-SQL 语句中,带有小数点的常量自动转换为 numeric 数据值,且必然使用最小的精度和小数位数。例如,常量 12.345 被转换为 numeric 值,其精度为 5,小数位为 3。

从 decimal 或 numeric 向 float 或 real 转换会导致精度损失。从 int、smallint、tinyint、float、real、money 或 smallmoney 向 decimal 或 numeric 转换会导致溢出。

默认情况下,在将数字转换为较低精度和小数位数的 decimal 或 numeric 值时,SQL Server 使用舍入法。然而,如果 SET ARITHABORT 选项为 ON,当发生溢出时,SQL Server 会出现错误。若仅损失精度和小数位数,则不会产生错误。

 

 

Float 的科学计数法与值的问题,问题的根源在于 float 类型本身是一种不精确的数据表示方法, 也就是说, 你放一个数据进去, 拿出来的时候可能会存在一点点点误差, 而这点点点误差在做数据比较的时候就会导致数据不一致.

posted @ 2012-03-09 17:03 青蛙學堂 阅读(917) | 评论 (0)编辑 收藏

C# 获取文件名及扩展名


 
C# 获取文件名及扩展名
2011年12月20日 星期二 22:02

C# 获取文件名及扩展名

string aFirstName = aFile.Substring(aFile.LastIndexOf("\\") + 1, (aFile.LastIndexOf(".") - aFile.LastIndexOf("\\") - 1));  //文件名
string aLastName = aFile.Substring(aFile.LastIndexOf(".") + 1, (aFile.Length - aFile.LastIndexOf(".") - 1));   //扩展名

string strFilePaht="文件路径";
Path.GetFileNameWithoutExtension(strFilePath);这个就是获取文件名的

。。。。。。。。。。。。。。。。

详见网址:http://dalaoyer.com/article.php?id=375


posted @ 2012-03-08 19:36 青蛙學堂 阅读(43720) | 评论 (5)编辑 收藏

ContentType--文件下载类型

Response.ContentType 详细列表
不同的ContentType 会影响客户端所看到的效果.默认的ContentType为 text/html 也就是网页格式.
代码如:
<% response.ContentType ="text/html" %> 
<!--#i nclude virtual="/ContentType.html" -->

显示的为网页,而
<% response.ContentType ="text/plain" %> 
<!--#i nclude virtual="/sscript/ContentType.html" -->

则会显示html原代码.

以下为一些常用的 ContentType
GIF images 
<% response.ContentType ="image/gif" %> 
<!--#i nclude virtual="/myimage.gif" -->

JPEG images 
<% response.ContentType ="image/jpeg" %> 
<!--#i nclude virtual="/myimage.jpeg" -->

TIFF images 
<% response.ContentType ="image/tiff" %> 
<!--#i nclude virtual="/myimage.tiff" -->

MICROSOFT WORD document 
<% response.ContentType ="application/msword" %> 
<!--#i nclude virtual="/myfile.doc" -->

RTF document 
<% response.ContentType ="application/rtf" %> 
<!--#i nclude virtual="/myfile.rtf" -->

MICROSOFT EXCEL document 
<% response.ContentType ="application/x-excel" %> 
<!--#i nclude virtual="/myfile.xls" -->

MICROSOFT POWERPOINT document 
<% response.ContentType ="application/ms-powerpoint" %> 
<!--#i nclude virtual="/myfile.pff" -->

PDF document 
<% response.ContentType ="application/pdf" %> 
<!--#i nclude virtual="/myfile.pdf" -->

ZIP document 
<% response.ContentType ="application/zip" %> 
<!--#i nclude virtual="/myfile.zip" -->



下面是更详细的ContentType
'ez' => 'application/andrew-inset', 
'hqx' => 'application/mac-binhex40', 
'cpt' => 'application/mac-compactpro', 
'doc' => 'application/msword', 
'bin' => 'application/octet-stream', 
'dms' => 'application/octet-stream', 
'lha' => 'application/octet-stream', 
'lzh' => 'application/octet-stream', 
'exe' => 'application/octet-stream', 
'class' => 'application/octet-stream', 
'so' => 'application/octet-stream', 
'dll' => 'application/octet-stream', 
'oda' => 'application/oda', 
'pdf' => 'application/pdf', 
'ai' => 'application/postscript', 
'eps' => 'application/postscript', 
'ps' => 'application/postscript', 
'smi' => 'application/smil', 
'smil' => 'application/smil', 
'mif' => 'application/vnd.mif', 
'xls' => 'application/vnd.ms-excel', 
'ppt' => 'application/vnd.ms-powerpoint', 
'wbxml' => 'application/vnd.wap.wbxml', 
'wmlc' => 'application/vnd.wap.wmlc', 
'wmlsc' => 'application/vnd.wap.wmlscriptc', 
'bcpio' => 'application/x-bcpio', 
'vcd' => 'application/x-cdlink', 
'pgn' => 'application/x-chess-pgn', 
'cpio' => 'application/x-cpio', 
'csh' => 'application/x-csh', 
'dcr' => 'application/x-director', 
'dir' => 'application/x-director', 
'dxr' => 'application/x-director', 
'dvi' => 'application/x-dvi', 
'spl' => 'application/x-futuresplash', 
'gtar' => 'application/x-gtar', 
'hdf' => 'application/x-hdf', 
'js' => 'application/x-javascript', 
'skp' => 'application/x-koan', 
'skd' => 'application/x-koan', 
'skt' => 'application/x-koan', 
'skm' => 'application/x-koan', 
'latex' => 'application/x-latex', 
'nc' => 'application/x-netcdf', 
'cdf' => 'application/x-netcdf', 
'sh' => 'application/x-sh', 
'shar' => 'application/x-shar', 
'swf' => 'application/x-shockwave-flash', 
'sit' => 'application/x-stuffit', 
'sv4cpio' => 'application/x-sv4cpio', 
'sv4crc' => 'application/x-sv4crc', 
'tar' => 'application/x-tar', 
'tcl' => 'application/x-tcl', 
'tex' => 'application/x-tex', 
'texinfo' => 'application/x-texinfo', 
'texi' => 'application/x-texinfo', 
't' => 'application/x-troff', 
'tr' => 'application/x-troff', 
'roff' => 'application/x-troff', 
'man' => 'application/x-troff-man', 
'me' => 'application/x-troff-me', 
'ms' => 'application/x-troff-ms', 
'ustar' => 'application/x-ustar', 
'src' => 'application/x-wais-source', 
'xhtml' => 'application/xhtml+xml', 
'xht' => 'application/xhtml+xml', 
'zip' => 'application/zip', 
'au' => 'audio/basic', 
'snd' => 'audio/basic', 
'mid' => 'audio/midi', 
'midi' => 'audio/midi', 
'kar' => 'audio/midi', 
'mpga' => 'audio/mpeg', 
'mp2' => 'audio/mpeg', 
'mp3' => 'audio/mpeg', 
'aif' => 'audio/x-aiff', 
'aiff' => 'audio/x-aiff', 
'aifc' => 'audio/x-aiff', 
'm3u' => 'audio/x-mpegurl', 
'ram' => 'audio/x-pn-realaudio', 
'rm' => 'audio/x-pn-realaudio', 
'rpm' => 'audio/x-pn-realaudio-plugin', 
'ra' => 'audio/x-realaudio', 
'wav' => 'audio/x-wav', 
'pdb' => 'chemical/x-pdb', 
'xyz' => 'chemical/x-xyz', 
'bmp' => 'image/bmp', 
'gif' => 'image/gif', 
'ief' => 'image/ief', 
'jpeg' => 'image/jpeg', 
'jpg' => 'image/jpeg', 
'jpe' => 'image/jpeg', 
'png' => 'image/png', 
'tiff' => 'image/tiff', 
'tif' => 'image/tiff', 
'djvu' => 'image/vnd.djvu', 
'djv' => 'image/vnd.djvu', 
'wbmp' => 'image/vnd.wap.wbmp', 
'ras' => 'image/x-cmu-raster', 
'pnm' => 'image/x-portable-anymap', 
'pbm' => 'image/x-portable-bitmap', 
'pgm' => 'image/x-portable-graymap', 
'ppm' => 'image/x-portable-pixmap', 
'rgb' => 'image/x-rgb', 
'xbm' => 'image/x-xbitmap', 
'xpm' => 'image/x-xpixmap', 
'xwd' => 'image/x-xwindowdump', 
'igs' => 'model/iges', 
'iges' => 'model/iges', 
'msh' => 'model/mesh', 
'mesh' => 'model/mesh', 
'silo' => 'model/mesh', 
'wrl' => 'model/vrml', 
'vrml' => 'model/vrml', 
'css' => 'text/css', 
'html' => 'text/html', 
'htm' => 'text/html', 
'asc' => 'text/plain', 
'txt' => 'text/plain', 
'rtx' => 'text/richtext', 
'rtf' => 'text/rtf', 
'sgml' => 'text/sgml', 
'sgm' => 'text/sgml', 
'tsv' => 'text/tab-separated-values', 
'wml' => 'text/vnd.wap.wml', 
'wmls' => 'text/vnd.wap.wmlscript', 
'etx' => 'text/x-setext', 
'xsl' => 'text/xml', 
'xml' => 'text/xml', 
'mpeg' => 'video/mpeg', 
'mpg' => 'video/mpeg', 
'mpe' => 'video/mpeg', 
'qt' => 'video/quicktime', 
'mov' => 'video/quicktime', 
'mxu' => 'video/vnd.mpegurl', 
'avi' => 'video/x-msvideo', 
'movie' => 'video/x-sgi-movie', 
'ice' => 'x-conference/x-cooltalk' 

//---------------------下面是从资源文件获取图片。并显示
 public class GetImage
    {
        public static System.Drawing.Image GetSrc(string name)
        {
            System.Resources.ResourceManager rm = new ResourceManager("ClassLibrary.ResourceTestImg",
       System.Reflection.Assembly.GetExecutingAssembly());//ResourceTestImg为资源文件名称,ClassLibrary//为命名空间
            return rm.GetObject(name) as System.Drawing.Image;
        }
       
    }

显示代码
 protected void Page_Load(object sender, EventArgs e)
 {

            System.Drawing.Image img = ClassLibrary.GetImage.GetSrc("_15958260");
           //_15958260为在ResourceTestImg.resx资源管理窗口中看到资源图片名称
                     
            img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}

posted @ 2012-03-08 19:30 青蛙學堂 阅读(6972) | 评论 (0)编辑 收藏

sqlserver-2008--file上传下载

数据库:sql server 2008 express

表:

CREATE TABLE [dbo].[filetest](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [fs] [varbinary](max) NULL
) ON [PRIMARY]

 

写入:

 protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection sconn =new SqlConnection("Server=192.168.1.11\\sqlexpress,1433; Database=DBCustomer; User Id=sa; Password=1234");
            string FileName;
            string FilePath = this.FileUpload1.PostedFile.FileName;
            Stream FileStream = FileUpload1.PostedFile.InputStream;
            FileName = Path.GetFileName(FilePath);
            if (FileName != null && FileName != "")
            {
                int FileLen = FileUpload1.PostedFile.ContentLength;
                byte[] FileData = new Byte[FileLen];
                int n = FileStream.Read(FileData, 0, FileLen);
                FileStream.Close();
                SqlCommand com = new SqlCommand();
                com.CommandText = "insert into filetest(fs) values(@fs)";
                com.Parameters.Add(new System.Data.SqlClient.SqlParameter("@fs", System.Data.SqlDbType.Image, FileData.Length, "fs"));
                com.Connection = sconn;
                com.Parameters["@fs"].Value = FileData;
                com.Connection.Open();
                com.ExecuteNonQuery();
                com.Connection.Close();
            }
        }

读取

SqlConnection sconn =new SqlConnection("Server=192.168.1.11\\sqlexpress,1433; Database=DBCustomer; User Id=sa; Password=1234");

//根据不同文件类型,设定ContentType 。
                //Response.ContentType = "application/vnd.ms-excel";
                //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.ContentType = "application/pdf";
                this.Response.Clear();
                SqlCommand selcom = new SqlCommand();
                selcom.CommandText = "select fs from filetest order by id desc";
                selcom.Connection = sconn;
                selcom.Connection.Open();
                SqlDataReader dr = selcom.ExecuteReader();
                dr.Read();
                Byte[] b = new Byte[(dr.GetBytes(0, 0, null, 0, int.MaxValue))];
                dr.GetBytes(0, 0, b, 0, b.Length);
                dr.Close();
                selcom.Connection.Close();
                System.IO.Stream fs = this.Response.OutputStream;
                fs.Write(b, 0, b.Length);

                fs.Close();
                this.Response.End();

posted @ 2012-03-08 16:53 青蛙學堂 阅读(651) | 评论 (1)编辑 收藏

把word存入sqlserver

/*如何把word存入sqlserver数据库,并且读取的时候还是用word读取.
建立table
create table myimages(sno int,imgfield image);
建立c#工程,添加引用(reference->add->brower->office安装文件夹->office11->msword.ole,然后什么都不用问了,等待...,然后拷贝下代码,具体功能见注释*/
using system;
using system.drawing;
using system.collections;
using system.componentmodel;
using system.windows.forms;
using system.data;
using system.data.sqlclient;
using system.io;

namespace writefile
{
 /// <summary>
 /// summary description for form1.
 /// </summary>
 public class form1 : system.windows.forms.form
 {
  private system.windows.forms.button button1;
  private system.windows.forms.textbox textbox1;
  private system.windows.forms.button button2;
  private system.windows.forms.button button3;
  /// <summary>
  /// required designer variable.
  /// </summary>
  private system.componentmodel.container components = null;

  public form1()
  {
   //
   // required for windows form designer support
   //
   initializecomponent();

   //
   // todo: add any constructor code after initializecomponent call
   //
  }

  /// <summary>
  /// clean up any resources being used.
  /// </summary>
  protected override void dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null) 
    {
     components.dispose();
    }
   }
   base.dispose( disposing );
  }

  #region windows form designer generated code
  /// <summary>
  /// required method for designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void initializecomponent()
  {
   this.button1 = new system.windows.forms.button();
   this.textbox1 = new system.windows.forms.textbox();
   this.button2 = new system.windows.forms.button();
   this.button3 = new system.windows.forms.button();
   this.suspendlayout();
   // 
   // button1
   // 
   this.button1.location = new system.drawing.point(576, 320);
   this.button1.name = "button1";
   this.button1.size = new system.drawing.size(112, 23);
   this.button1.tabindex = 0;
   this.button1.text = "savefiletodb";
   this.button1.click += new system.eventhandler(this.button1_click);
   // 
   // textbox1
   // 
   this.textbox1.location = new system.drawing.point(0, 0);
   this.textbox1.multiline = true;
   this.textbox1.name = "textbox1";
   this.textbox1.size = new system.drawing.size(568, 424);
   this.textbox1.tabindex = 1;
   this.textbox1.text = "textbox1";
   // 
   // button2
   // 
   this.button2.location = new system.drawing.point(600, 104);
   this.button2.name = "button2";
   this.button2.tabindex = 2;
   this.button2.text = "readword";
   this.button2.click += new system.eventhandler(this.button2_click);
   // 
   // button3
   // 
   this.button3.location = new system.drawing.point(568, 184);
   this.button3.name = "button3";
   this.button3.size = new system.drawing.size(112, 23);
   this.button3.tabindex = 3;
   this.button3.text = "readfromdb";
   this.button3.click += new system.eventhandler(this.button3_click);
   // 
   // form1
   // 
   this.autoscalebasesize = new system.drawing.size(5, 13);
   this.clientsize = new system.drawing.size(712, 429);
   this.controls.add(this.button3);
   this.controls.add(this.button2);
   this.controls.add(this.textbox1);
   this.controls.add(this.button1);
   this.name = "form1";
   this.text = "form1";

 this.load += new system.eventhandler(this.form1_load);
   this.resumelayout(false);


  }
  #endregion

  /// <summary>
  /// the main entry point for the application.
  /// </summary>
  [stathread]
  static void main() 
  {
   application.run(new form1());
  }

  private void button1_click(object sender, system.eventargs e)//word存入sqlserver
  {
     dbmana dm=new dbmana();
   sqlconnection con=dm.getcon();//
另外的类,返回sqlserver连接,用的时候要自己建立连接

   
   sqldataadapter comm=new sqldataadapter("select * from myimages",con);
   sqlcommandbuilder scb=new sqlcommandbuilder(comm);//
只有这样才能保证dataadapter可以update
   dataset ds=new dataset("myimages");
   comm.fill(ds,"myimages");
   comm.missingschemaaction=missingschemaaction.addwithkey;
   datarow newrow;
   newrow=ds.tables[0].newrow();
   filestream fs=new filestream(@"e:\club.doc",filemode.open,fileaccess.read);
   byte[] data=new byte[fs.length];
   fs.read(data,0,convert.toint32(fs.length));//
文件读到byte[]
   fs.close();
   comm.fill(ds,"myimages");
   newrow["id"]=3;
   newrow["description"]="this is a file";
   newrow["imgfield"]=data;//insert the binary stream
   ds.tables["myimages"].rows.add(newrow);
   comm.update(ds,"myimages");//update,then the table is update
   con.close();

   /*try
   {
    con.open();
    ds.tables[0].rows[0]["content"]=data;
   }
   catch(exception ex)
   {
    this.textbox1.text=ex.tostring();


   }
   finally
   {
    fs.close();
    con.close();

   }*/

  
  }

  private void form1_load(object sender, system.eventargs e)
  {
   
  }

  private void button2_click(object sender, system.eventargs e)//read the word file
  {
      object nothing=system.reflection.missing.value;
     object filename=@"e:\club.doc";
   word.applicationclass ap=new word.applicationclass();
      word.document doc=ap.documents.open(ref filename,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing);
   
   ap.visible=true;
      
   
  
  }

  private void button3_click(object sender, system.eventargs e)//read from table,and临时存放,便于读取然后可以删掉
  {
   dbmana dm=new dbmana();
  sqlconnection con=dm.getcon();
   //sqlcommand com=new sqlcommand("select imgfield from myimages",con);
   dataset ds=new dataset();
   sqldataadapter comm=new sqldataadapter("select imgfield from myimages",con);
   sqlcommandbuilder scb=new sqlcommandbuilder(comm);
   byte[] data=new byte[0];
      comm.fill(ds,"myimages");
   datarow newrow;
   newrow=ds.tables["myimages"].rows[3];
   data=(byte[])newrow["imgfield"];
   int arraysize=new int();//
注意这句话
   arraysize=data.getupperbound(0);

   filestream fs=new filestream(@"e:\test.doc",filemode.openorcreate,fileaccess.write);
   try
   {
    
    
    fs.write(data,0,arraysize);
   }
   catch(exception ex)
   {
    this.textbox1.text=ex.tostring();

   }
   finally
   {
    con.close();
    fs.close();
    
   }

   
   
  
  }
 }

 

posted @ 2012-03-08 15:05 青蛙學堂 阅读(652) | 评论 (0)编辑 收藏

Fileupload--sqlserver2005



数据库:Sql Server 2005 

字段:image_file     类型:image

前台控件:FileUpLoad(fuImage)、上传button(btnUpload)、查询button、GridVew

图片上传代码:

    protected void btnUpload_Click(object sender, EventArgs e)
    {

        byte[] imgBinaryData = this.fuImage.FileBytes;
       
        {

            string sql = "insert into image(image_file) values (@img)";
            string strconn ="Data Source=SMARTGUOLEI;Initial Catalog=web;Persist Security Info=True;User ID=sa;Password=sa;";
            SqlConnection sqlConn = new SqlConnection(strconn);
            SqlCommand sqlComm = new SqlCommand(sql, sqlConn);
            sqlComm.Parameters.Add("@img", SqlDbType.Image);//添加参数
            sqlComm.Parameters["@img"].Value = imgBinaryData;//为参数赋值
            sqlConn.Open();
            sqlComm.ExecuteNonQuery();
            sqlConn.Close();
            Response.Write("<script language='javascript'>alert('保存成功!')</script>");

        }

此代码应该是运行正常,因为我通过SqlDataSource控制的配置数据源的功能,在最后完成的那一步,通过查询的功能看到上传上来的图像。

数据查询代码:

protected void Button1_Click(object sender, EventArgs e)
    {
        string s;
        s = "select * from image";
        OleDbConnection Conn = null;
        DataSet ds = null;
        string strConn = "Data Source=SMARTGUOLEI;Initial Catalog=web;Persist Security Info=True;User ID=sa;Password=sa;Provider=SQLOLEDB.1;";
        Conn = new OleDbConnection(strConn); //实例化一个连接
        OleDbCommand Cmd = new OleDbCommand(s);
        OleDbDataAdapter ODA = new OleDbDataAdapter(Cmd); //实例化一个数据适配器
        ODA.SelectCommand.Connection = Conn;
        Conn.Open();//记得要打开连接
        //ODA.SelectCommand.CommandText=s;
        ds = new DataSet();
        ODA.Fill(ds, "image");
        this.GridView1.DataSource = ds;
        this.GridView1.DataBind();

    }

此代码应该是运行正常的,因为我在数据库表的设计上,加了一个int编号主键(自动增值 ),在GridView显示时,可以将那个编号查询出来。

 

GridView的前台代码:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:ImageField DataImageUrlField="image_file">
            </asp:ImageField>
        </Columns>
    </asp:GridView>


posted @ 2012-03-08 14:54 青蛙學堂 阅读(279) | 评论 (0)编辑 收藏

FileUpload--example

在VS2008中,使用<asp:UploadFile控件

前台页面

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpload.aspx.cs" Inherits="WebApplication1.FileUpload" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml" >  
  6. <head runat="server">  
  7.     <title>无标题</title>  
  8.     <script type="text/javascript">  
  9.         function checkType() {  
  10.             //得到上传文件的值  
  11.             var fileName = document.getElementById('FileUpLoad1').value;  
  12.             //返回String对象中字符串最后出现的位置。  
  13.             var seat = fileName.lastIndexOf(".");  
  14.             //返回位于String对象中指定位置的子字符串并转换为小写  
  15.             var extension = fileName.substring(seat).toLowerCase();  
  16.             var allowed = [".xls", ".xlsx"];  
  17.             for (var i = 0; i < allowed.length; i++) {  
  18.                 if (!(allowed[i] != extension)) {  
  19.                     return true;  
  20.                 }  
  21.             }  
  22.             alert("不支持" + extension + "格式");  
  23.             return false;  
  24.         }  
  25.     </script>  
  26. </head>  
  27. <body>  
  28.     <form id="form1" runat="server">  
  29.     <div>  
  30.         <asp:FileUpload ID="FileUpLoad1" runat="server" />  
  31.         <br />  
  32.         <asp:Button ID="btnFileUpload" runat="server"   
  33.             Text="文件上传" OnClientClick="return checkType()"   
  34.             onclick="btnFileUpload_Click" />  
  35.         <asp:Label ID="lblMessage" runat="server"></asp:Label>  
  36.     </div>  
  37.     </form>  
  38. </body>  
  39. </html>  


 

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;

namespace WebApplication1
{
    public partial class FileUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnFileUpload_Click(object sender, EventArgs e)
        {
            if (FileUpLoad1.HasFile)
            {
                //判断文件是否小于4MB
                if (FileUpLoad1.PostedFile.ContentLength < 4194304)
                {

                   HttpPostedFile file = FileUpLoad1.PostedFile;
                   string str=file.FileName;
                   string filename2 = str.Substring(str.LastIndexOf(".")).ToString().Trim();
                   string filename1 = DateTime.Now.Ticks.ToString()+filename2;
                   file.SaveAs(Server.MapPath("./upload/"+filename1));//将用户上传的文件保存到服务器上.                    

 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("./upload/"+filename1) + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
                    OleDbConnection Oleconn = new OleDbConnection(strConn);
                    string strExcel = "";
                    OleDbDataAdapter excelCommand = null;
                    DataSet excel_ds = new DataSet();
                    strExcel = "select * from [sheet1$]";
                    try
                    {
                        Oleconn.Open();
                        excelCommand = new OleDbDataAdapter(strExcel, Oleconn);
                        excelCommand.Fill(excel_ds, "exdtSource");//得到dataset
                        lblMessage.Text = "上传成功!";
                    }
                    catch (Exception ex)
                    {
                        lblMessage.Text = "出现异常,无法上传!";
                    }
                    finally
                    {
                        Oleconn.Close();
                        Oleconn.Dispose();
                    }

                }
                else
                {
                    lblMessage.Text = "上传文件不能大于10MB!";
                }
            }
            else
            {
                lblMessage.Text = "尚未选择文件!";
            }
            
        }
    }
}

posted @ 2012-03-08 14:18 青蛙學堂 阅读(361) | 评论 (0)编辑 收藏

文件上传-下载

文件的上传下载是我们在实际项目开发过程中经常需要用到的技术,这里给出几种常见的方法,本文主要内容包括:

1、如何解决文件上传大小的限制

2、以文件形式保存到服务器

3、转换成二进制字节流保存到数据库以及下载方法

4、上传Internet上的资源 

第一部分:

首先我们来说一下如何解决ASP.NET中的文件上传大小限制的问题,我们知道在默认情况下ASP.NET的文件上传大小限制为2M,一般情况下,我们可以采用更改WEB.Config文件 <system.web> </system.web>中 自定义最大文件大小,如下:
        <httpRuntime executionTimeout="600" maxRequestLength="951200" useFullyQualifiedRedirectUrl="true" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100"/>这样上传文件的最大值就变成了4M,但这样并不能让我们无限的扩大 MaxRequestLength的值,因为ASP.NET会将全部文件载入内存后,再加以处理。解决的方法是利用隐含的 HttpWorkerRequest,用它的GetPreloadedEntityBody和ReadEntityBody方法从IIS为ASP.NET 建立的pipe里分块读取数据。实现方法如下:

IServiceProviderprovider=(IServiceProvider)HttpContext.Current;
HttpWorkerRequestwr=(HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
byte[]bs=wr.GetPreloadedEntityBody();
.
if(!wr.IsEntireEntityBodyIsPreloaded())
{
intn=1024;
byte[]bs2=newbyte[n];
while(wr.ReadEntityBody(bs2,n)>0)
{
..
}
}

这样就可以解决了大文件的上传问题了。

第二部分:

下面我们来介绍如何以文件形式将客户端的一个文件上传到服务器并返回上传文件的一些基本信息。

首先我们定义一个类,用来存储上传的文件的信息(返回时需要)。

public class FileUpLoad
{
public FileUpLoad()
{}
/**//// <summary>
/// 上传文件名称
/// </summary>
public string FileName
{
get
{
return fileName;
}
set
{
fileName = value;
}
}
private string fileName;

/**//// <summary>
/// 上传文件路径
/// </summary>
public string FilePath
{
get
{
return filepath;
}
set
{
filepath = value;
}
}
private string filepath;

/**//// <summary>
/// 文件扩展名
/// </summary>
public string FileExtension
{
get
{
return fileExtension;
}
set
{
fileExtension = value;
}
}
private string fileExtension;
}

另外我们还可以在配置文件中限制上传文件的格式(App.Config):

<?xml version="1.0" encoding="gb2312" ?>
<Application> 
<FileUpLoad>
<Format>.jpg|.gif|.png|.bmp</Format>
</FileUpLoad>
</Application>

这样我们就可以开始写我们的上传文件的方法了,如下:

public FileUpLoad UpLoadFile(HtmlInputFile InputFile,string filePath,string myfileName,bool isRandom)
{
FileUpLoad fp = new FileUpLoad();
string fileName,fileExtension;
string saveName;

//
//建立上传对象
//
HttpPostedFile postedFile = InputFile.PostedFile;

fileName = System.IO.Path.GetFileName(postedFile.FileName);
fileExtension = System.IO.Path.GetExtension(fileName);

//
//根据类型确定文件格式
//
AppConfig app = new AppConfig();
string format = app.GetPath("FileUpLoad/Format");

//
//如果格式都不符合则返回
//
if(format.IndexOf(fileExtension)==-1)
{
throw new ApplicationException("上传数据格式不合法");
}

//
//根据日期和随机数生成随机的文件名
//
if(myfileName != string.Empty)
{
fileName = myfileName; 
}

if(isRandom)
{
Random objRand = new Random();
System.DateTime date = DateTime.Now;
//生成随机文件名
saveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + Convert.ToString(objRand.Next(99)*97 + 100);
fileName = saveName + fileExtension;
}

string phyPath = HttpContext.Current.Request.MapPath(filePath);

//判断路径是否存在,若不存在则创建路径
DirectoryInfo upDir = new DirectoryInfo(phyPath);
if(!upDir.Exists)
{
upDir.Create();
}

//
//保存文件
//
try
{
postedFile.SaveAs(phyPath + fileName);

fp.FilePath = filePath + fileName;
fp.FileExtension = fileExtension;
fp.FileName = fileName;
}
catch
{
throw new ApplicationException("上传失败!");
}

//返回上传文件的信息
return fp;
}

然后我们在上传文件的时候就可以调用这个方法了,将返回的文件信息保存到数据库中,至于下载,就直接打开那个路径就OK了。

第三部分:

这里我们主要说一下如何以二进制的形式上传文件以及下载。首先说上传,方法如下:

public byte[] UpLoadFile(HtmlInputFile f_IFile)
{
//获取由客户端指定的上传文件的访问
HttpPostedFile upFile=f_IFile.PostedFile;
//得到上传文件的长度
int upFileLength=upFile.ContentLength; 
//得到上传文件的客户端MIME类型
string contentType = upFile.ContentType;
byte[] FileArray=new Byte[upFileLength];

Stream fileStream=upFile.InputStream; 

fileStream.Read(FileArray,0,upFileLength);
return FileArray;
}

这个方法返回的就是上传的文件的二进制字节流,这样我们就可以将它保存到数据库了。下面说一下这种形式的下载,也许你会想到这种方式的下载就是新建一 个aspx页面,然后在它的Page_Load()事件里取出二进制字节流,然后再读出来就可以了,其实这种方法是不可取的,在实际的运用中也许会出现无 法打开某站点的错误,我一般采用下面的方法:

首先,在Web.config中加入:

<add verb="*" path="openfile.aspx" type="RuixinOA.Web.BaseClass.OpenFile, RuixinOA.Web"/>

这表示我打开openfile.aspx这个页面时,系统就会自动转到执行RuixinOA.Web.BaseClass.OpenFile 这个类里的方法,具体实现如下:

using System;
using System.Data;
using System.Web;
using System.IO;
using Ruixin.WorkFlowDB;
using RXSuite.Base;
using RXSuite.Component;
using RuixinOA.BusinessFacade;

namespace RuixinOA.Web.BaseClass
{
/**//// <summary>
/// NetUFile 的摘要说明。
/// </summary>
public class OpenFile : IHttpHandler
{
public void ProcessRequest(HttpContext context) 
{
//从数据库中取出要下载的文件信息
RuixinOA.BusinessFacade.RX_OA_FileManager os = new RX_OA_FileManager();
EntityData data = os.GetFileDetail(id);

if(data != null && data.Tables["RX_OA_File"].Rows.Count > 0)
{
DataRow dr = (DataRow)data.Tables["RX_OA_File"].Rows[0];
context.Response.Buffer = true;
context.Response.Clear();
context.Response.ContentType = dr["CContentType"].ToString(); 
context.Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(dr["CTitle"].ToString()));
context.Response.BinaryWrite((Byte[])dr["CContent"]);
context.Response.Flush();
context.Response.End();
}
}
public bool IsReusable 
{  
get { return true;} 
}
}
}

执行上面的方法后,系统会提示用户选择直接打开还是下载。这一部分我们就说到这里。

第四部分:

这一部分主要说如何上传一个Internet上的资源到服务器。

首先需要引用 System.Net 这个命名空间,然后操作如下: 

HttpWebRequest hwq = (HttpWebRequest)WebRequest.Create("http://localhost/pwtest/webform1.aspx");
HttpWebResponse hwr = (HttpWebResponse)hwq.GetResponse();
byte[] bytes = new byte[hwr.ContentLength];
Stream stream = hwr.GetResponseStream();
stream.Read(bytes,0,Convert.ToInt32(hwr.ContentLength));
//HttpContext.Current.Response.BinaryWrite(bytes);

HttpWebRequest 可以从Internet上读取文件,因此可以很好的解决这个问题。

posted @ 2012-03-08 13:17 青蛙學堂 阅读(278) | 评论 (0)编辑 收藏

仅列出标题
共43页: First 14 15 16 17 18 19 20 21 22 Last 
<2025年2月>
2627282930311
2345678
9101112131415
16171819202122
2324252627281
2345678

导航

统计

常用链接

留言簿(8)

随笔分类

随笔档案

收藏夹

青蛙学堂

最新评论

阅读排行榜

评论排行榜