生成随机编码 / SQL语句导入导出大全 //金额阿拉伯数字转换为中文的自定义函数

生成随机编码
--取得随机数的视图
CREATE VIEW v_RAND
AS
SELECT re=STUFF(RAND(),1,2,'')
GO
--生成随机编号的函数
CREATE FUNCTION f_RANDBH(@BHLen int)
RETURNS varchar(50)
AS
BEGIN
 DECLARE @r varchar(50)
 IF NOT(ISNULL(@BHLen,0) BETWEEN 1 AND 50)
  SET @BHLen=10
 SELECT @r=CHAR(
   CASE WHEN SUBSTRING(re,1,1)>5 THEN 97 ELSE 65 end
   +(SUBSTRING(re,1,1)
   +SUBSTRING(re,2,1)
   +SUBSTRING(re,3,1))%26)
  +CHAR(
   CASE WHEN SUBSTRING(re,4,1)>5 THEN 97 ELSE 65 end
   +(SUBSTRING(re,4,1)
   +SUBSTRING(re,5,1)
   +SUBSTRING(re,6,1))%26)
 FROM v_RAND
 WHILE LEN(@r)<@BHLen
  SELECT @r=@r+CHAR(
    CASE WHEN SUBSTRING(re,1,1)>5 THEN 97 ELSE 65 end
    +(SUBSTRING(re,1,1)
    +SUBSTRING(re,2,1)
    +SUBSTRING(re,3,1))%26)
   +CHAR(
    CASE WHEN SUBSTRING(re,4,1)>5 THEN 97 ELSE 65 end
    +(SUBSTRING(re,4,1)
    +SUBSTRING(re,5,1)
    +SUBSTRING(re,6,1))%26)
  FROM v_RAND
 RETURN(LEFT(@r,@BHLen))
END
GO
--调用
SELECT dbo.f_RANDBH(6),dbo.f_RANDBH(8)
--结果: YZVBOj   LASCrhSO
 
 
14:29 |  固定链接 | 引用通告 (0) | 记录它
SQL语句导入导出大全

/*******  导出到excel
EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:/temp1.xls -c -q -S"GNETDATA/GNETDATA" -U"sa" -P""'

/***********  导入Excel
SELECT *
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
  'Data Source="c:/test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions

/*动态文件名
declare @fn varchar(20),@s varchar(1000)
set @fn = 'c:/test.xls'
set @s ='''Microsoft.Jet.OLEDB.4.0'',
''Data Source="'+@fn+'";User ID=Admin;Password=;Extended properties=Excel 5.0'''
set @s = 'SELECT * FROM OpenDataSource ('+@s+')...sheet1$'
exec(@s)
*/

SELECT cast(cast(科目编号 as numeric(10,2)) as nvarchar(255))+' ' 转换后的别名
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
  'Data Source="c:/test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions

/********************** EXCEL导到远程SQL
insert OPENDATASOURCE(
         'SQLOLEDB',
         'Data Source=远程ip;User ID=sa;Password=密码'
         ).库名.dbo.表名 (列名1,列名2)
SELECT 列名1,列名2
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
  'Data Source="c:/test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions


/** 导入文本文件
EXEC master..xp_cmdshell 'bcp dbname..tablename in c:/DT.txt -c -Sservername -Usa -Ppassword'

/** 导出文本文件
EXEC master..xp_cmdshell 'bcp dbname..tablename out c:/DT.txt -c -Sservername -Usa -Ppassword'

EXEC master..xp_cmdshell 'bcp "Select * from dbname..tablename" queryout c:/DT.txt -c -Sservername -Usa -Ppassword'

导出到TXT文本,用逗号分开
exec master..xp_cmdshell 'bcp "库名..表名" out "d:/tt.txt" -c -t ,-U sa -P password'


BULK INSERT 库名..表名
FROM 'c:/test.txt'
WITH (
    FIELDTERMINATOR = ';',
    ROWTERMINATOR = '/n'
)


--/* dBase IV文件
select * from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'dBase IV;HDR=NO;IMEX=2;DATABASE=C:/','select * from [客户资料4.dbf]')
--*/

--/* dBase III文件
select * from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'dBase III;HDR=NO;IMEX=2;DATABASE=C:/','select * from [客户资料3.dbf]')
--*/

--/* FoxPro 数据库
select * from openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;SourceType=DBF;SourceDB=c:/',
'select * from [aa.DBF]')
--*/

/**************导入DBF文件****************/
select * from openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;
SourceDB=e:/VFP98/data;
SourceType=DBF',
'select * from customer where country != "USA" order by country')
go
/***************** 导出到DBF ***************/
如果要导出数据到已经生成结构(即现存的)FOXPRO表中,可以直接用下面的SQL语句

insert into openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;SourceType=DBF;SourceDB=c:/',
'select * from [aa.DBF]')
select * from 表

说明:
SourceDB=c:/  指定foxpro表所在的文件夹
aa.DBF        指定foxpro表的文件名.

 


/*************导出到Access********************/
insert into openrowset('Microsoft.Jet.OLEDB.4.0',
   'x:/A.mdb';'admin';'',A表) select * from 数据库名..B表

/*************导入Access********************/
insert into B表 selet * from openrowset('Microsoft.Jet.OLEDB.4.0',
   'x:/A.mdb';'admin';'',A表)

文件名为参数
declare @fname varchar(20)
set @fname = 'd:/test.mdb'
exec('SELECT a.* FROM opendatasource(''Microsoft.Jet.OLEDB.4.0'',
    '''+@fname+''';''admin'';'''', topics) as a ')

SELECT *
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
  'Data Source="f:/northwind.mdb";Jet OLEDB:Database Password=123;User ID=Admin;Password=;')...产品

*********************  导入 xml 文件

DECLARE @idoc int
DECLARE @doc varchar(1000)
--sample XML document
SET @doc ='
<root>
  <Customer cid= "C1" name="Janine" city="Issaquah">
      <Order oid="O1" date="1/20/1996" amount="3.5" />
      <Order oid="O2" date="4/30/1997" amount="13.4">Customer was very satisfied
      </Order>
   </Customer>
   <Customer cid="C2" name="Ursula" city="Oelde" >
      <Order oid="O3" date="7/14/1999" amount="100" note="Wrap it blue
             white red">
            <Urgency>Important</Urgency>
            Happy Customer.
      </Order>
      <Order oid="O4" date="1/20/1996" amount="10000"/>
   </Customer>
</root>
'
-- Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc

-- Execute a SELECT statement using OPENXML rowset provider.
SELECT *
FROM OPENXML (@idoc, '/root/Customer/Order', 1)
      WITH (oid     char(5),
            amount  float,
            comment ntext 'text()')
EXEC sp_xml_removedocument @idoc

 

???????

/**********************Excel导到Txt****************************************/
想用
select * into opendatasource(...) from opendatasource(...)
实现将一个Excel文件内容导入到一个文本文件

假设Excel中有两列,第一列为姓名,第二列为很行帐号(16位)
且银行帐号导出到文本文件后分两部分,前8位和后8位分开。


邹健:
如果要用你上面的语句插入的话,文本文件必须存在,而且有一行:姓名,银行账号1,银行账号2
然后就可以用下面的语句进行插入
注意文件名和目录根据你的实际情况进行修改.

insert into
opendatasource('MICROSOFT.JET.OLEDB.4.0'
,'Text;HDR=Yes;DATABASE=C:/'
)...[aa#txt]
--,aa#txt)
--*/
select 姓名,银行账号1=left(银行账号,8),银行账号2=right(银行账号,8)
from
opendatasource('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;IMEX=2;DATABASE=c:/a.xls'
--,Sheet1$)
)...[Sheet1$]

 

如果你想直接插入并生成文本文件,就要用bcp

declare @sql varchar(8000),@tbname varchar(50)

--首先将excel表内容导入到一个全局临时表
select @tbname='[##temp'+cast(newid() as varchar(40))+']'
 ,@sql='select 姓名,银行账号1=left(银行账号,8),银行账号2=right(银行账号,8)
 into '+@tbname+' from
opendatasource(''MICROSOFT.JET.OLEDB.4.0''
,''Excel 5.0;HDR=YES;IMEX=2;DATABASE=c:/a.xls''
)...[Sheet1$]'
exec(@sql)

--然后用bcp从全局临时表导出到文本文件
set @sql='bcp "'+@tbname+'" out "c:/aa.txt" /S"(local)" /P"" /c'
exec master..xp_cmdshell @sql

--删除临时表
exec('drop table '+@tbname)


/********************导整个数据库*********************************************/

用bcp实现的存储过程


/*
 实现数据导入/导出的存储过程
         根据不同的参数,可以实现导入/导出整个数据库/单个表
 调用示例:
--导出调用示例
----导出单个表
exec file2table 'zj','','','xzkh_sa..地区资料','c:/zj.txt',1
----导出整个数据库
exec file2table 'zj','','','xzkh_sa','C:/docman',1

--导入调用示例
----导入单个表
exec file2table 'zj','','','xzkh_sa..地区资料','c:/zj.txt',0
----导入整个数据库
exec file2table 'zj','','','xzkh_sa','C:/docman',0

*/
if exists(select 1 from sysobjects where name='File2Table' and objectproperty(id,'IsProcedure')=1)
 drop procedure File2Table
go
create procedure File2Table
@servername varchar(200)  --服务器名
,@username varchar(200)   --用户名,如果用NT验证方式,则为空''
,@password varchar(200)   --密码
,@tbname varchar(500)   --数据库.dbo.表名,如果不指定:.dbo.表名,则导出数据库的所有用户表
,@filename varchar(1000)  --导入/导出路径/文件名,如果@tbname参数指明是导出整个数据库,则这个参数是文件存放路径,文件名自动用表名.txt
,@isout bit      --1为导出,0为导入
as
declare @sql varchar(8000)

if @tbname like '%.%.%' --如果指定了表名,则直接导出单个表
begin
 set @sql='bcp '+@tbname
  +case when @isout=1 then ' out ' else ' in ' end
  +' "'+@filename+'" /w'
  +' /S '+@servername
  +case when isnull(@username,'')='' then '' else ' /U '+@username end
  +' /P '+isnull(@password,'')
 exec master..xp_cmdshell @sql
end
else
begin --导出整个数据库,定义游标,取出所有的用户表
 declare @m_tbname varchar(250)
 if right(@filename,1)<>'/' set @filename=@filename+'/'

 set @m_tbname='declare #tb cursor for select name from '+@tbname+'..sysobjects where xtype=''U'''
 exec(@m_tbname)
 open #tb
 fetch next from #tb into @m_tbname
 while @@fetch_status=0
 begin
  set @sql='bcp '+@tbname+'..'+@m_tbname
   +case when @isout=1 then ' out ' else ' in ' end
   +' "'+@filename+@m_tbname+'.txt " /w'
   +' /S '+@servername
   +case when isnull(@username,'')='' then '' else ' /U '+@username end
   +' /P '+isnull(@password,'')
  exec master..xp_cmdshell @sql
  fetch next from #tb into @m_tbname
 end
 close #tb
 deallocate #tb
end
go


/************* Oracle **************/
EXEC sp_addlinkedserver 'OracleSvr',
   'Oracle 7.3',
   'MSDAORA',
   'ORCLDB'
GO

delete from openquery(mailser,'select *  from yulin')

select *  from openquery(mailser,'select *  from yulin')

update openquery(mailser,'select * from  yulin where id=15')set disorder=555,catago=888

insert into openquery(mailser,'select disorder,catago from  yulin')values(333,777)

 

补充:

对于用bcp导出,是没有字段名的.

用openrowset导出,需要事先建好表.

用openrowset导入,除ACCESS及EXCEL外,均不支持非本机数据导入

 
14:26 |  固定链接 | 引用通告 (0) | 记录它
金额阿拉伯数字转换为中文的自定义函数
CREATE FUNCTION ChangeBigSmall
(@ChangeMoney money)  
RETURNS VarChar(100) AS  

BEGIN
    Declare    @String1    char(20)
    Declare    @String2    char(30)
    Declare    @String4    Varchar(100)
    Declare @String3     Varchar(100)    --从原A值中取出的值
    Declare @i         int        --循环变量
    Declare @J         Int        --A的值乘以100的字符串长度
    Declare @Ch1         Varchar(100)    --数字的汉语读法
    Declare @Ch2         Varchar(100)    --数字位的汉字读法
    Declare @Zero         Int        --用来计算连续有几个零
    Declare    @ReturnValue    VarChar(100)

    Select  @ReturnValue = ''
    Select     @String1 = '零壹贰叁肆伍陆柒捌玖'
    Select    @String2 = '万仟佰拾亿仟佰拾万仟佰拾元角分'

    Select @String4 = Cast(@ChangeMoney*100 as int)    

    select @J=len(cast((@ChangeMoney*100) as int))

    Select @String2=Right(@String2,@J)

    Select    @i = 1

    while    @i<= @j Begin

        Select @String3 = Substring(@String4,@i,1)

        if @String3<>'0' Begin

            Select     @Ch1 = Substring(@String1, Cast(@String3 as Int) + 1, 1)
            Select    @Ch2 = Substring(@String2, @i, 1)
            Select    @Zero = 0                    --表示本位不为零
        end
        else Begin
            If (@Zero = 0) Or (@i = @J - 9) Or (@i = @J - 5) Or (@i = @J - 1)
                        Select @Ch1 = '零'
                    Else
                        Select @Ch1 = ''

                    Select @Zero = @Zero + 1             --表示本位为0
                        
            --如果转换的数值需要扩大,那么需改动以下表达式 I 的值。
            Select @Ch2 = ''

                If @i = @J - 10  Begin
                        Select @Ch2 = '亿'
                        Select @Zero = 0
            end
                    
            If @i = @J - 6 Begin
                        Select @Ch2 = '万'
                        Select @Zero = 0
            end
                    
            if @i = @J - 2 Begin
                        Select @Ch2 = '元'
                        Select @Zero = 0
            end
                    
            If @i = @J
                        Select @Ch2 = '整'
                        
        end    

        Select @ReturnValue = @ReturnValue + @Ch1 + @Ch2

        select @i = @i+1
    end

    --最后将多余的零去掉
    If CharIndex('仟仟',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '仟仟', '仟')

    If CharIndex('佰佰',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '佰佰', '佰')

        If CharIndex('零元',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零元', '元')
    
        If CharIndex('零万',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零万', '万')
   
        If CharIndex('零亿',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零亿', '亿')
    
        If CharIndex('零整',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零整', '整')
    
    If CharIndex('零佰',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零佰', '零')

    If CharIndex('零仟',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零仟', '零')

    If CharIndex('元元',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '元元', '元')

    return @ReturnValue

END
 
14:25 |  固定链接 | 引用通告 (0) | 记录它
金额阿拉伯数字转换为中文的存储过程
Create    Procedure    AtoC
    @ChangeMoney    Money    
as
    Set Nocount ON
    Declare    @String1    char(20)
    Declare    @String2    char(30)
    Declare    @String4    Varchar(100)
    Declare @String3     Varchar(100)    --从原A值中取出的值
        Declare @i         int        --循环变量
    Declare @J         Int        --A的值乘以100的字符串长度
        Declare @Ch1         Varchar(100)    --数字的汉语读法
        Declare @Ch2         Varchar(100)    --数字位的汉字读法
    Declare @Zero         Int        --用来计算连续有几个零
    Declare    @ReturnValue    VarChar(100)

    Select @ReturnValue = ''
    Select     @String1 = '零壹贰叁肆伍陆柒捌玖'
    Select    @String2 = '万仟佰拾亿仟佰拾万仟佰拾元角分'

    Select @String4 = Cast(@ChangeMoney*100 as int)    

    select @J=len(cast((@ChangeMoney*100) as int))

    Select @String2=Right(@String2,@J)

    Select    @i = 1

    while    @i<= @j Begin

        Select @String3 = Substring(@String4,@i,1)

        if @String3<>'0' Begin

            Select     @Ch1 = Substring(@String1, Cast(@String3 as Int) + 1, 1)
            Select    @Ch2 = Substring(@String2, @i, 1)
            Select    @Zero = 0                    --表示本位不为零
        end
        else Begin
            If (@Zero = 0) Or (@i = @J - 9) Or (@i = @J - 5) Or (@i = @J - 1)
                        Select @Ch1 = '零'
                    Else
                        Select @Ch1 = ''

                    Select @Zero = @Zero + 1             --表示本位为0
                        
            --如果转换的数值需要扩大,那么需改动以下表达式 I 的值。
            Select Ch2 = ''

                If @i = @J - 10  Begin
                        Select @Ch2 = '亿'
                        Select @Zero = 0
            end
                    
            If @i = @J - 6 Begin
                        Select @Ch2 = '万'
                        Select @Zero = 0
            end
                    
            if @i = @J - 2 Begin
                        Select @Ch2 = '元'
                        Select @Zero = 0
            end
                    
            If @i = @J
                        Select @Ch2 = '整'
                        
        end    

        Select @ReturnValue = @ReturnValue + @Ch1 + @Ch2

        select @i = @i+1
    end

    --最后将多余的零去掉
    If CharIndex('仟仟',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '仟仟', '仟')

    If CharIndex('佰佰',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '佰佰', '佰')

        If CharIndex('零元',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零元', '元')
    
        If CharIndex('零万',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零万', '万')
   
        If CharIndex('零亿',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零亿', '亿')
    
        If CharIndex('零整',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零整', '整')
    
    If CharIndex('零佰',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零佰', '零')

    If CharIndex('零仟',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '零仟', '零')

    If CharIndex('元元',@ReturnValue) <> 0
            Select @ReturnValue = Replace(@ReturnValue, '元元', '元')
    
    Select @ReturnValue
GO
 
14:22 |  固定链接 | 引用通告 (0) | 记录它
12月13日
执子之手,与子偕老
执子之手,与子偕老,这该是一幅两个人同撑起一方天空的风景,象两棵独立的大树,我们共同撑起一方天空,枝叶在蓝天下盛放,树根在地底下相互扶持,风也罢霜也罢,雨也罢雪也罢,执子之手,每一刻都是如此的美好,每一刻都是一首动人的情诗,每一刻都值得用所有的时光去回味……
执子之手,与子偕老,这是一种并肩站立,共同凝望太阳升起、落下的感觉;是一种天变地变情不变的感觉,只是想紧紧握住你的手,什么话也不说,慢慢地陪你走过今生今世,来生来世……
执子之手,与子偕老,当你哭泣的时候,有人陪你伤心,倾听你诉说,为你抚平凌乱的发和憔悴的颜容,告诉你明天依旧阳光灿烂;当你笑容明媚的时候,整个世界都和你一起明媚,而他静静地站在一旁,微笑着看着你和阳光一般地灿烂……
 
 
 
 
0:57 |  固定链接 | 引用通告 (0) | 记录它
母亲的谎言
儿时,小男孩家很穷,吃饭时,饭常常不够吃,母亲就把自己碗里的饭分给孩子吃。母亲说,孩子们,快吃吧,我不饿!——母亲撒的第一个谎。

男孩长身体的时候,勤劳的母亲常用周日休息时间去县郊农村河沟里捞些鱼来给孩子们补钙。鱼很好吃,鱼汤也很鲜。孩子们吃鱼的时候,母亲就在一旁啃鱼骨头,用舌头舔鱼骨头上的肉渍。男孩心疼,就把自己碗里的鱼夹到母亲碗里,请母亲吃鱼。母亲不吃,母亲又用筷子把鱼夹回男孩的碗里。母亲说,孩子,快吃吧,我不爱吃鱼!——母亲撒的第二个谎。

上初中了,为了缴够男孩和哥姐的学费,当缝纫工的母亲就去居委会领些火柴盒拿回家来,晚上糊了挣点分分钱补点家用。有个冬天,男孩半夜醒来,看到母亲还躬着身子在油灯下糊火柴盒。男孩说,母亲,睡了吧,明早您还要上班呢。母亲笑笑,说,孩子,快睡吧,我不困!——母亲撒的第三个谎。

高考那年,母亲请了假天天站在考点门口为参加高考的男孩助阵。时逢盛夏,烈日当头,固执的母亲在烈日下一站就是几个小时。考试结束的铃声响了,母亲迎上去递过一杯用罐头瓶泡好的浓茶叮嘱孩子喝了,茶亦浓,情更浓。望着母亲干裂的嘴唇和满头的汗珠,男孩将手中的罐头瓶反递过去请母亲喝。母亲说,孩子,快喝吧,我不渴!——母亲撒的第四个谎。

       父亲病逝之后,母亲又当爹又当娘,K着自己在缝纫社里那点微薄收入含辛茹苦拉扯着几个孩子,供他们念书,日子过得苦不堪言。胡同路口电线杆下修表的李叔叔知道后,大事小事就找岔过来打个帮手,搬搬煤,挑挑水,送些钱粮来帮补男孩的家里。人非草木,孰能无情。左邻右舍对此看在眼里,记在心里!——母亲撒的第五个谎

       孩和她的哥姐大学毕业参加工作后,下了岗的母亲就在附近农贸市场摆了个小摊维持生活。身在外地工作的孩子们知道后就常常寄钱回来补贴母亲,母亲坚决不要,并将钱退了回去。母亲说,我有钱!——母亲撒的第六个谎。

       男孩留校任教两年,后又考取了美国一所名牌大学的博士生,毕业后留在美国一家科研机构工作,待遇相当丰厚,条件好了,身在异国的男孩想把母亲接来享享清福却被老人回绝了。母亲说,我不习惯!——母亲撒的第七个谎。晚年,母亲患了胃癌,住进了医院,远在大西洋彼岸的男孩乘飞机赶回来时,术后的母亲已是奄奄一息了。母亲老了,望着被病魔折磨得死去活来的母亲,男孩悲痛欲绝,潸然泪下。母亲却说,孩子,别哭,我不疼。——母亲撒的第八个谎。
       说完,在“谎言”里度过了一生的母亲终于闭上了眼睛。 
       母爱是伟大的!
 
0:43 |  固定链接 | 引用通告 (0) | 记录它
人生中10件无能为力的事
倒向你的墙!
离你而去的人
流逝的时间
没有选择的出身
莫名其妙的孤独
无可奈何的遗忘
永远的过去
别人的嘲笑
不可避免的死亡
不可救药的喜欢
 
0:41 |  固定链接 | 引用通告 (0) | 记录它
12月6日
生成流水号
--生成流水号
--创建测试表
create table test(id varchar(18),  --流水号,日期(8位)+时间(4位)+流水号(4位)
 name varchar(10)  --其他字段
)
go
--创建生成流水号的触发器
create trigger t_insert on test
INSTEAD OF insert
as
declare @id varchar(18),@id1 int,@head varchar(12)
select * into #tb from inserted
set @head=convert(varchar,getdate(),112)+replace(convert(varchar(5),getdate(),108),':','')
select @id=max(id) from test where id like @head+'%'
if @id is null
 set @id1=0
else
 set @id1=cast(substring(@id,13,4) as int)
update #tb set @id1=@id1+1
 ,id=@head+right('0000'+cast(@id1 as varchar),4)
insert into test select * from #tb
go

--插入数据,进行测试
insert into test(name)
select 'aa'
union all select 'bb'
union all select 'cc'
--修改系统时间,再插入数据测试一次
insert into test(name)
select 'aa'
union all select 'bb'
union all select 'cc'
--显示测试结果
select * from test

--删除测试环境
drop table test
/*--测试结果
id                 name      
------------------ ----------
2004022720430001   aa
2004022720430002   bb
2004022720430003   cc
2004022720430004   aa
2004022720430005   bb
2004022720430006   cc
(所影响的行数为 6 行)
--*/
 
22:17 |  固定链接 | 引用通告 (0) | 记录它
生成纯字母随机编号的示例(大小写混合).sql
--取得随机数的视图
CREATE VIEW v_RAND
AS
SELECT re=STUFF(RAND(),1,2,'')
GO
--生成随机编号的函数
CREATE FUNCTION f_RANDBH(@BHLen int)
RETURNS varchar(50)
AS
BEGIN
 DECLARE @r varchar(50)
 IF NOT(ISNULL(@BHLen,0) BETWEEN 1 AND 50)
  SET @BHLen=10
 SELECT @r=CHAR(
   CASE WHEN SUBSTRING(re,1,1)>5 THEN 97 ELSE 65 end
   +(SUBSTRING(re,1,1)
   +SUBSTRING(re,2,1)
   +SUBSTRING(re,3,1))%26)
  +CHAR(
   CASE WHEN SUBSTRING(re,4,1)>5 THEN 97 ELSE 65 end
   +(SUBSTRING(re,4,1)
   +SUBSTRING(re,5,1)
   +SUBSTRING(re,6,1))%26)
 FROM v_RAND
 WHILE LEN(@r)<@BHLen
  SELECT @r=@r+CHAR(
    CASE WHEN SUBSTRING(re,1,1)>5 THEN 97 ELSE 65 end
    +(SUBSTRING(re,1,1)
    +SUBSTRING(re,2,1)
    +SUBSTRING(re,3,1))%26)
   +CHAR(
    CASE WHEN SUBSTRING(re,4,1)>5 THEN 97 ELSE 65 end
    +(SUBSTRING(re,4,1)
    +SUBSTRING(re,5,1)
    +SUBSTRING(re,6,1))%26)
  FROM v_RAND
 RETURN(LEFT(@r,@BHLen))
END
GO
--调用
SELECT dbo.f_RANDBH(6),dbo.f_RANDBH(8)
--结果: YZVBOj   LASCrhSO
 
 
22:16 |  固定链接 | 引用通告 (0) | 记录它
C++编程人员容易犯的10个C#错
C++编程人员容易犯的10个C#错误


我们知道, C#的语法与C++非常相似,实现从C++向C#的转变,其困难不在于语言本身,而在于熟悉.NET的可管理环境和对.NET框架的理解。

尽管C#与C++在语法上的变化是很小的,几乎不会对我们有什么影响,但有些变化却足以使一些粗心的C++编程人员时刻铭记在心。在本篇文章中我们将讨论C++编程人员最容易犯的十个错误。

陷阱1: 没有明确的结束方法
几乎可以完全肯定地说,对于大多数C++编程人员而言,C#与C++最大的不同之处就在于碎片收集。这也意味着编程人员再也无需担心内存泄露和确保删除所有没有用的指针。但我们再也无法精确地控制杀死无用的对象这个过程。事实上,在C#中没有明确的destructor。

如果使用非可管理性资源,在不使用这些资源后,必须明确地释放它。对资源的隐性控制是由Finalize方法(也被称为finalizer)提供的,当对象被销毁时,它就会被碎片收集程序调用收回对象所占用的资源。

finalizer 应该只释放被销毁对象占用的非可管理性资源,而不应牵涉到其他对象。如果在程序中只使用了可管理性资源,那就无需也不应当执行Finalize方法,只有在非可管理性资源的处理中才会用到Finalize方法。由于finalizer需要占用一定的资源,因此应当只在需要它的方法中执行 finalizer。

直接调用一个对象的Finalize方法是绝对不允许的(除非是在子类的Finalize中调用基础类的Finalize。),碎片收集程序会自动地调用Finalize。

从语法上看,C#中的destructor与C++非常相似,但其实它们是完全不同的。C#中的destructor只是定义Finalize方法的捷径。因此,下面的二段代码是有区别的:

~MyClass()
{
// 需要完成的任务
}

MyClass.Finalize()
{
// 需要完成的任务
base.Finalize();
}

 

错误2:Finalize和Dispose使用谁?
从上面的论述中我们已经很清楚,显性地调用finalizer是不允许的,它只能被碎片收集程序调用。如果希望尽快地释放一些不再使用的数量有限的非可管理性资源(如文件句柄),则应该使用IDisposable界面,这一界面有个 Dispose方法,它能够帮你完成这个任务。Dispose是无需等待Finalize被调用而能够释放非可管理性资源的方法。

如果已经使用了Dispose方法,则应当阻止碎片收集程序再对相应的对象执行Finalize方法。为此,需要调用静态方法 GC.SuppressFinalize,并将相应对象的指针传递给它作为参数,Finalize方法就能调用Dispose方法了。据此,我们能够得到如下的代码:

public void Dispose()
{
// 完成清理操作

// 通知GC不要再调用Finalize方法
GC.SuppressFinalize(this);
}

public override void Finalize()
{
Dispose();
base.Finalize();
}

对于有些对象,可能调用Close方法就更合适(例如,对于文件对象调用Close就比Dispose更合适),可以通过创建一个private属性的 Dispose方法和public属性的Close方法,并让Close调用Dispose来实现对某些对象调用Close方法。

由于不能确定一定会调用Dispose,而且finalizer的执行也是不确定的(我们无法控制GC会在何时运行),C#提供了一个Using语句来保证 Dispose方法会在尽可能早的时间被调用。一般的方法是定义使用哪个对象,然后用括号为这些对象指定一个活动的范围,当遇到最内层的括号时, Dispose方法就会被自动调用,对该对象进行处理。

using System.Drawing;
class Tester
{
public static void Main()
{
using (Font theFont = new Font("Arial", 10.0f))
{
//使用theFont对象

} // 编译器将调用Dispose处理theFont对象

Font anotherFont = new Font("Courier",12.0f);

using (anotherFont)
{
// 使用anotherFont对象

} // 编译器将调用Dispose处理anotherFont对象

}

}

 

在本例的第一部分中,Font对象是在Using语句中创建的。当Using语句结束时,系统就会调用Dispose,对Font对象进行处理。在本例的第二部分,Font对象是在Using语句外部创建的,在决定使用它时,再将它放在Using语句内,当Using语句结束时,系统就会调用 Dispose。

Using语句还能防止其他意外的发生,保证系统一定会调用Dispose。

错误3:C#中的值型变量和引用型变量是有区别的
与C++一样,C#也是一种强类型编程语言。C#中的数据类型被分为了二大类:C#语言本身所固有的数据类型和用户自定义数据类型,这一点也与C++相似。

此外,C#语言还把变量分为值类型和引用类型。除非是被包含在一个引用类型中,值类型变量的值保留在栈中,这一点与C++中的变量非常相似。引用类型的变量也是栈的一种,它的值是堆中对象的地址,与C++中的指针非常地相似。值类型变量的值被直接传递给方法,引用型变量在被作为参数传递给方法时,传递的是索引。

类和界面可以创建引用类变量,但需要指出的是,结构数据类型是C#的一种内置数据类型,同时也是一种值型的数据类型。

错误4:注意隐性的数据类型转换
Boxing 和unboxing是使值型数据类型被当作索引型数据类型使用的二个过程。值型变量可以被包装进一个对象中,然后再被解包回值型变量。包括内置数据类型在内的所有C#中的数据类型都可以被隐性地转化为一个对象。包装一个值型变量就会生成一个对象的实例,然后将变量拷贝到实例中。

Boxing是隐性的,如果在需要索引型数据类型的地方使用了值型数据类型的变量,值型变量就会隐性地转化为索引型数据类型的变量。Boxing会影响代码执行的性能,因此应当尽量避免,尤其是在数据量较大的时候。

如果要将一个打包的对象转换回原来的值型变量,必须显性地对它进行解包。解包需要二个步骤:首先对对象实例进行检查,确保它们是由值型的变量被包装成的;第二步将实例中的值拷贝到值型变量中。为了确保解包成功,被解包的对象必须是通过打包一个值型变量的值生成的对象的索引。

using System;
public class UnboxingTest
{
public static void Main()
{
int i = 123;

//打包
object o = i;

// 解包(必须是显性的)
int j = (int) o;
Console.WriteLine("j: {0}", j);
}
}

如果被解包的对象是无效的,或是一个不同数据类型对象的索引,就会产生InvalidCastException异外。

错误5:结构与对象是有区别的
C++中的结构与类差不多,唯一的区别是,在缺省状态下,结构的访问权限是public,其继承权限也是public。一些C++编程人员将结构作为数据对象,但这只是一个约定而非是必须这样的。

在C#中,结构只是一个用户自定义的数据类型,并不能取代类。尽管结构也支持属性、方法、域和操作符,但不支持继承和destructor。

更重要的是,类是一种索引型数据类型,结构是值型数据类型。因此,结构在表达无需索引操作的对象方面更有用。结构在数组操作方面的效率更高,而在集合的操作方面则效率较低。集合需要索引,结构必须打包才适合在集合的操作中使用,类在较大规模的集合操作中的效率更高。

错误6:虚方法必须被明确地覆盖
在C# 语言中,编程人员在覆盖一个虚方法时必须显性地使用override关健字。假设一个Window类是由A公司编写的,ListBox和 RadioButton类是由B公司的和编程人员在购买的A公司编写的Window类的基础上编写的,B公司的编程人员对包括Window类未来的变化情况在内的设计知之甚少。

如果B公司的一位编程人员要在ListBox上添加一个Sort方法:

public class ListBox : Window
{
public virtual void Sort() {"}
}

在A公司发布新版的Window类之前,这不会有任何问题。如果A公司的编程人员也在Window类中添加了一个Sort方法。

public class Window
{
// "
public virtual void Sort() {"}
}

在C ++中,Windows类中的Sort方法将成为ListBox类中Sort方法的基础方法,在希望调用Windows类中的Sort方法时, ListBox类中的Sort方法就会被调用。在C#中,虚拟函数总是被认为是虚拟调度的根。也就是说,一旦C#发现一个虚拟的方法,就不会再在虚拟链中查找其他虚拟方法。如果ListBox再次被编译,编译器就会生成一个警告信息:

"/class1.cs(54,24): warning CS0114: 'ListBox.Sort()' hides
inherited member 'Window.Sort()'.

要使当前的成员覆盖原来的方法,就需要添加override关健字,或者添加new关健字。

要消除警告信息,编程人员必须搞清楚他想干什么。可以在ListBox类中的Sort方法前添加new,表明它不应该覆盖Window中的虚方法:

public class ListBox : Window
{
public new virtual void Sort() {"}

这样就可以清除警告信息。如果编程人员确实希望覆盖掉Window中的方法,就必须使用override关健字来显性地表明其意图。

 

错误7:类成员变量的初始化
C#中的初始化与C++中不同。假设有一个带有private性质的成员变量age的Person类, Employee是由继承Person类而生成的,它有一个private性质的salaryLevel成员变量。在C++中,我们可以在 Employee的构造器的初始化部分初始化salaryLevel,如下面的代码所示:

Employee::Employee(int theAge, int theSalaryLevel):
Person(theAge) // 初始化基础类
salaryLevel(theSalaryLevel) // 初始化成员变量
{
// 构造器的代码
}

这种方法在C#中是非法的。尽管仍然可以初始化基础类,但象上面的代码那样对成员变量初始化就会引起编译错误。在C#中,我们可以在定义成员变量时的同时对它进行初始化:

Class Employee : public Person
{
// 成员变量的定义
private salaryLevel = 3; // 初始化
}

注意:必须明确地定义每个变量的访问权限。

错误8:布尔型变量与整型变量是两回事儿
if( someFuncWhichReturnsAValue() )

在C#中,布尔型变量与整型变量并不相同,因此下面的代码是不正确的:

if( someFuncWhichReturnsAValue() )

if someFuncWhichReturnsAValue返回零表示false,否则表示true的想法已经行不通了。这样的好处是原来存在的将赋值运算与相等相混淆的错误就不会再犯了。因此下面的代码:

if ( x = 5 )

在编译时就会出错,因为x=5只是把5赋给了X,而不是一个布尔值。

错误9:switch语句中会有些语句执行不到
在C#中,如果一个switch语句执行了一些操作,则程序就可能不能执行到下一个语句。因此,尽管下面的代码在C++中是合法的,但在C#中却不合法:

switch (i)
{
case 4:
CallFuncOne();
case 5: // 错误,不会执行到这里
CallSomeFunc();
}

要实现上面代码的目的,需要使用一个goto语句:

switch (i)
{
case 4:
CallFuncOne();
goto case 5;
case 5:
CallSomeFunc();
}

如果case语句不执行任何代码,则所有的语句都会被执行。如下面的代码:

switch (i)
{
case 4: // 能执行到
case 5: // 能执行到
case 6:
CallSomeFunc();
}

错误10:C#中的变量要求明确地赋值
在C#中,所有的变量在使用前都必须被赋值。因此,可以在定义变量时不对它进行初始化,如果在把它传递给一个方法前,必须被赋值。

如果只是通过索引向方法传递一个变量,并且该变量是方法的输出变量,这是就会带来问题。例如,假设有一个方法,它返回当前时间的小时、分、秒,如果象下面这样编写代码:

int theHour;
int theMinute;
int theSecond;
timeObject.GetTime( ref theHour, ref theMinute, ref theSecond)

如果在使用theHour、theMinute和theSecond这三个变量之前没有对它们进行初始化,就会产生一个编译错误:

Use of unassigned local variable 'theHour'
Use of unassigned local variable 'theMinute'
Use of unassigned local variable 'theSecond'

我们可以通过将这些变量初始化为0或其他对方法的返回值没有影响的值,以解决编译器的这个小问题:

int theHour = 0;
int theMinute = 0;
int theSecond = 0;
timeObject.GetTime( ref theHour, ref theMinute, ref theSecond)

这样就有些太麻烦了,这些变量传递给GetTime方法,然后被改变而已。为了解决这一问题,C#专门针对这一情况提供了out参数修饰符,它可以使一个参数无需初始化就可以被引用。例如,GetTime中的参数对它本身没有一点意义,它们只是为了表达该方法的输出。在方法中返回之前,Out参数中必须被指定一个值。下面是经过修改后的GetTime方法:

public void GetTime(out int h, out int m, out int s)
{
h = Hour;
m = Minute;
s = Second;
}

下面是新的GetTime方法的调用方法:

timeObject.GetTime( out theHour, out theMinute, out theSecond);

 
22:14 |  固定链接 | 引用通告 (0) | 记录它
用C#实现生成PDF文档
using System;
using System.IO;
using System.Text;
using System.Collections;
 
namespace PDFGenerator
{
 
public class PDFGenerator
{
static float pageWidth = 594.0f;
static float pageDepth = 828.0f;
static float pageMargin = 30.0f;
static float fontSize = 20.0f;
static float leadSize = 10.0f;
 
static StreamWriter pPDF=new StreamWriter("E://myPDF.pdf");
 
static MemoryStream mPDF= new MemoryStream();
 
static void ConvertToByteAndAddtoStream(string strMsg)
{
    Byte[] buffer=null;
    buffer=ASCIIEncoding.ASCII.GetBytes(strMsg);
    mPDF.Write(buffer,0,buffer.Length); 
    buffer=null;
}
 
static string xRefFormatting(long xValue)
{
    string strMsg =xValue.ToString();
    int iLen=strMsg.Length;
    if (iLen<10)
    {
        StringBuilder s=new StringBuilder();
        int i=10-iLen;
        s.Append('0',i);
        strMsg=s.ToString() + strMsg;
    }
    return strMsg;
}
 
static void Main(string[] args)
{
    ArrayList xRefs=new ArrayList();
    //Byte[] buffer=null;
    float yPos =0f;
    long streamStart=0;
    long streamEnd=0;
    long streamLen =0;
    string strPDFMessage=null;
    //PDF文档头信息
    strPDFMessage="%PDF-1.1/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
 
    xRefs.Add(mPDF.Length);
    strPDFMessage="1 0 obj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage="<< /Length 2 0 R >>/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage="stream/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    /**/PDF文档描述
    streamStart=mPDF.Length;
    //字体
    strPDFMessage="BT/n/F0 " + fontSize +" Tf/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    //PDF文档实体高度
    yPos = pageDepth - pageMargin;
    strPDFMessage=pageMargin + " " + yPos +" Td/n" ;
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage= leadSize+" TL/n" ;
    ConvertToByteAndAddtoStream(strPDFMessage);
 
    //实体内容
    strPDFMessage= "(http://www.wenhui.org)Tj/n" ;
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage= "ET/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    streamEnd=mPDF.Length;
 
    streamLen=streamEnd-streamStart;
    strPDFMessage= "endstream/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    //PDF文档的版本信息
    xRefs.Add(mPDF.Length);
    strPDFMessage="2 0 obj/n"+ streamLen + "/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
 
    xRefs.Add(mPDF.Length);
    strPDFMessage="3 0 obj/n<</Type/Page/Parent 4 0 R/Contents 1 0 R>>/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
 
    xRefs.Add(mPDF.Length);
    strPDFMessage="4 0 obj/n<</Type /Pages /Count 1/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage="/Kids[/n3 0 R/n]/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage="/Resources<</ProcSet[/PDF/Text]/Font<</F0 5 0 R>> >>/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage="/MediaBox [ 0 0 "+ pageWidth + " " + pageDepth + " ]/n>>/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
 
    xRefs.Add(mPDF.Length);
    strPDFMessage="5 0 obj/n<</Type/Font/Subtype/Type1/BaseFont/Courier/Encoding/WinAnsiEncoding>>/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
 
    xRefs.Add(mPDF.Length);
    strPDFMessage="6 0 obj/n<</Type/Catalog/Pages 4 0 R>>/nendobj/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
 
    streamStart=mPDF.Length;
    strPDFMessage="xref/n0 7/n0000000000 65535 f /n";
    for(int i=0;i<xRefs.Count;i++)
    {
        strPDFMessage+=xRefFormatting((long) xRefs[i])+" 00000 n /n";
    }
    ConvertToByteAndAddtoStream(strPDFMessage);
    strPDFMessage="trailer/n<</n/Size "+ (xRefs.Count+1)+"/n/Root 6 0 R/n>>/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
 
    strPDFMessage="startxref/n" + streamStart+"/n%%EOF/n";
    ConvertToByteAndAddtoStream(strPDFMessage);
    mPDF.WriteTo(pPDF.BaseStream);
 
    mPDF.Close();
    pPDF.Close();
}
}
}

 
22:13 |  固定链接 | 引用通告 (0) | 记录它
c#中结构与类的区别
一.类与结构的示例比较: 
结构示例: 
public struct Person 

   string Name; 
   int  height; 
   int  weight 
public bool overWeight() 

    //implement something 


  类示例: 
   public class TestTime 
   { 
 int hours; 
 int minutes; 
 int seconds; 
 
public void passtime() 

  //implementation of behavior 

   } 
 调用过程: 
  public class Test 
  { 
public static ovid Main 

   Person Myperson=new Person      //声明结构 
   TestTime Mytime=New TestTime    //声明类 


从上面的例子中我们可以看到,类的声明和结构的声明非常类似,只是限定符后面是 struct 还是 class 的区别,而且使用时,定义新的结构和定义新的类的方法也非常类似。那么类和结构的具体区别是什么呢? 
 
二 .类与结构的差别 
1.             值类型与引用类型 
结构是值类型:值类型在堆栈上分配地址,所有的基类型都是结构类型,例如:int 对应System.int32 结构,string 对应 system.string 结构 ,通过使用结构可以创建更多的值类型 
类是引用类型:引用类型在堆上分配地址 
堆栈的执行效率要比堆的执行效率高,可是堆栈的资源有限,不适合处理大的逻辑复杂的对象。所以结构处理作为基类型对待的小对象,而类处理某个商业逻辑 
因为结构是值类型所以结构之间的赋值可以创建新的结构,而类是引用类型,类之间的赋值只是复制引用 
注: 
1.虽然结构与类的类型不一样,可是他们的基类型都是对象(object),c#中所有类型的基类型都是object 
2.虽然结构的初始化也使用了New 操作符可是结构对象依然分配在堆栈上而不是堆上,如果不使用“新建”(new),那么在初始化所有字段之前,字段将保持未赋值状态,且对象不可用 
  2.继承性 
     结构:不能从另外一个结构或者类继承,本身也不能被继承,虽然结构没有明确的用sealed声明,可是结构是隐式的sealed . 
     类:完全可扩展的,除非显示的声明sealed 否则类可以继承其他类和接口,自身也能被继承 
     注:虽然结构不能被继承 可是结构能够继承接口,方法和类继承接口一样 
例如:结构实现接口 
  interface IImage

{
    void Paint();
}
 
struct Picture : IImage
{
    public void Paint()
    {
         // painting code goes here
    }
    private int x, y, z;  // other struct members
}
 
  3.内部结构: 
结构: 
没有默认的构造函数,但是可以添加构造函数 
    没有析构函数 
    没有 abstract 和 sealed(因为不能继承) 
    不能有protected 修饰符 
    可以不使用new 初始化 
在结构中初始化实例字段是错误的 
类: 
 有默认的构造函数 
 有析构函数 
 可以使用 abstract 和 sealed 
有protected 修饰符 
必须使用new 初始化 
 
三.如何选择结构还是类 
   讨论了结构与类的相同之处和差别之后,下面讨论如何选择使用结构还是类: 
1.  堆栈的空间有限,对于大量的逻辑的对象,创建类要比创建结构好一些 
2.   结构表示如点、矩形和颜色这样的轻量对象,例如,如果声明一个含有 1000 个点对象的数组,则将为引用每个对象分配附加的内存。在此情况下,结构的成本较低。 
3.  在表现抽象和多级别的对象层次时,类是最好的选择
4.  大多数情况下该类型只是一些数据时,结构时最佳的选择 
 
22:13 |  固定链接 | 引用通告 (0) | 记录它
C#获取本地计算机名,IP,MAC地址
using System;
using System.Drawing;
using System.Management;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace MAC_IP_name
{
    /// <summary>
    /// Form1 的摘要说明。
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.TextBox txtMac;
        private System.Windows.Forms.TextBox txtIp;
        private System.Windows.Forms.TextBox txtName;
        private System.Windows.Forms.Label lblMac;
        private System.Windows.Forms.Label lblIp;
        private System.Windows.Forms.Label lblName;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.Container components = null;

        public Form1()
        {
            //
            // Windows 窗体设计器支持所必需的
            //
            InitializeComponent();

            //
            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
            //
        }

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows 窗体设计器生成的代码
        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.label4 = new System.Windows.Forms.Label();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.button2 = new System.Windows.Forms.Button();
            this.txtMac = new System.Windows.Forms.TextBox();
            this.txtIp = new System.Windows.Forms.TextBox();
            this.txtName = new System.Windows.Forms.TextBox();
            this.lblMac = new System.Windows.Forms.Label();
            this.lblIp = new System.Windows.Forms.Label();
            this.lblName = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("楷体_GB2312", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
            this.label4.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(128)), ((System.Byte)(128)));
            this.label4.Location = new System.Drawing.Point(49, 16);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(245, 26);
            this.label4.TabIndex = 7;
            this.label4.Text = "获取本机计算机名IP与MAC";
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.button2);
            this.groupBox1.Controls.Add(this.txtMac);
            this.groupBox1.Controls.Add(this.txtIp);
            this.groupBox1.Controls.Add(this.txtName);
            this.groupBox1.Controls.Add(this.lblMac);
            this.groupBox1.Controls.Add(this.lblIp);
            this.groupBox1.Controls.Add(this.lblName);
            this.groupBox1.Controls.Add(this.button1);
            this.groupBox1.Location = new System.Drawing.Point(16, 56);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(320, 208);
            this.groupBox1.TabIndex = 11;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "获取区";
            //
            // button2
            //
            this.button2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
            this.button2.Location = new System.Drawing.Point(184, 160);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(88, 32);
            this.button2.TabIndex = 18;
            this.button2.Text = "退出";
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // txtMac
            //
            this.txtMac.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(224)), ((System.Byte)(224)), ((System.Byte)(224)));
            this.txtMac.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
            this.txtMac.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(128)), ((System.Byte)(0)));
            this.txtMac.Location = new System.Drawing.Point(128, 110);
            this.txtMac.Name = "txtMac";
            this.txtMac.ReadOnly = true;
            this.txtMac.Size = new System.Drawing.Size(168, 21);
            this.txtMac.TabIndex = 17;
            this.txtMac.Text = "";
            //
            // txtIp
            //
            this.txtIp.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(224)), ((System.Byte)(224)), ((System.Byte)(224)));
            this.txtIp.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
            this.txtIp.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(128)), ((System.Byte)(0)));
            this.txtIp.Location = new System.Drawing.Point(128, 70);
            this.txtIp.Name = "txtIp";
            this.txtIp.ReadOnly = true;
            this.txtIp.Size = new System.Drawing.Size(168, 21);
            this.txtIp.TabIndex = 16;
            this.txtIp.Text = "";
            //
            // txtName
            //
            this.txtName.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(224)), ((System.Byte)(224)), ((System.Byte)(224)));
            this.txtName.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
            this.txtName.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(128)), ((System.Byte)(0)));
            this.txtName.Location = new System.Drawing.Point(128, 30);
            this.txtName.Name = "txtName";
            this.txtName.ReadOnly = true;
            this.txtName.Size = new System.Drawing.Size(168, 21);
            this.txtName.TabIndex = 15;
            this.txtName.Text = "";
            //
            // lblMac
            //
            this.lblMac.AutoSize = true;
            this.lblMac.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
            this.lblMac.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(0)), ((System.Byte)(64)));
            this.lblMac.Location = new System.Drawing.Point(32, 112);
            this.lblMac.Name = "lblMac";
            this.lblMac.Size = new System.Drawing.Size(88, 22);
            this.lblMac.TabIndex = 14;
            this.lblMac.Text = "MAC地址为:";
            //
            // lblIp
            //
            this.lblIp.AutoSize = true;
            this.lblIp.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
            this.lblIp.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(0)), ((System.Byte)(64)));
            this.lblIp.Location = new System.Drawing.Point(40, 72);
            this.lblIp.Name = "lblIp";
            this.lblIp.Size = new System.Drawing.Size(80, 22);
            this.lblIp.TabIndex = 13;
            this.lblIp.Text = "IP地址为:";
            //
            // lblName
            //
            this.lblName.AutoSize = true;
            this.lblName.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
            this.lblName.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(0)), ((System.Byte)(64)));
            this.lblName.Location = new System.Drawing.Point(24, 32);
            this.lblName.Name = "lblName";
            this.lblName.Size = new System.Drawing.Size(97, 22);
            this.lblName.TabIndex = 12;
            this.lblName.Text = "计算机名为:";
            //
            // button1
            //
            this.button1.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
            this.button1.Location = new System.Drawing.Point(48, 160);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(88, 32);
            this.button1.TabIndex = 11;
            this.button1.Text = "点击获取";
            this.button1.Click += new System.EventHandler(this.button1_Click_1);
            //
            // Form1
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.ClientSize = new System.Drawing.Size(352, 285);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.label4);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "IP,计算机名,MAC查询";
            this.groupBox1.ResumeLayout(false);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }

        private void button1_Click_1(object sender, System.EventArgs e)
        {
            string s="",mac="";
            //
            //name
            //
            string hostInfo = Dns.GetHostName();            

            //
            //IP
            System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;  
            for (int i = 0; i < addressList.Length; i ++)
            {
                s += addressList[i].ToString();
            }
            //
            //mac
            //


            ManagementClass mc;
            mc=new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc=mc.GetInstances();
            foreach(ManagementObject mo in moc)
            {
                if(mo["IPEnabled"].ToString()=="True")
                    mac=mo["MacAddress"].ToString();                    
            }


            txtName.Text=hostInfo;
            txtIp.Text=s;
            txtMac.Text=mac;


            button1.Enabled=false;
            button2.Focus();

        }

        private void button2_Click(object sender, System.EventArgs e)
        {
            Application.Exit();
        }
    }
}

 
22:11 |  固定链接 | 引用通告 (0) | 记录它
C#和SQL数据浏览分页
C#和SQL数据浏览分页

如果需要考虑如时间的过滤、其他条件的加入,可以在SQL语句进行编辑,普通的网站,下面的数据浏览分页

就可以了。

aspx代码:

<%@ Page language="c#" Codebehind="StockOrderFormBrower.aspx.cs" AutoEventWireup="false" Inherits="GSP.StockOrderFormBrower" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>

 <HEAD>
  <title>
   用C#和SQL结合进行数据浏览分页
  </title>
  <LINK href="css/main.css" type="text/css" rel="stylesheet">
  <meta http-equiv="Content-Type" content="text/html; charset=GB2312">
  <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
  <meta content="C#" name="CODE_LANGUAGE">
  <meta content="JavaScript" name="vs_defaultClientScript">
 </HEAD>
 
 <body MS_POSITIONING="GridLayout">
  <form id="form1" method="post" runat="server">
   <table id="ShowData" cellSpacing="0" cellPadding="0" align="center" border="0">
    <%ShowData();%><!--输出数据-->
   </table>
   <table align="right">
    <tr>
     <td>
      <%PageLoad_Count();%>
      <INPUT id="first" type="button" value="  |<  " name="first" runat="server"><!--第一页-->
      <INPUT id="prior" type="button" value="  <  " name="prior" runat="server"><!--上一页-->
      <INPUT id="next" type="button" value="  >  " name="next" runat="server"><!--下一页-->
      <INPUT id="last" type="button" value="  >|  " name="last" runat="server"><!--最后一页-->
     </td>
    </tr>
   </table>
  </form>
 </body>

</HTML>

aspx.cs代码:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace ASWBLM
{
 /// <summary>
 /// 
 /// </summary>
 public class UnionInfo : System.Web.UI.Page
 {                                   
  protected System.Web.UI.HtmlControls.HtmlInputButton first;
  protected System.Web.UI.HtmlControls.HtmlInputButton prior;
  protected System.Web.UI.HtmlControls.HtmlInputButton last;
  protected System.Web.UI.HtmlControls.HtmlInputButton next;


  protected static int CurrentPage = 1;//初始化开始页面
  protected static int RowCount = 0 ;//本页有多少条
  private static bool IsPrior = false;//有“前一页”
  private static bool IsNext = false;//有“下一页”
  private static bool IsLast = false;//有“最后一页”
  protected static int not_shown_records=0;//计算未显示记录数
  private static string startID = "";//设置上一页开始ID
  private static string endID = "";//设置下一页结束ID

  private static int page_count = 10;//初始化页面记录数


  private void Page_Load(object sender, System.EventArgs e)
  {   
   // 在此处放置用户代码以初始化页面
   if (!IsPostBack)
   {             
    this.CountRecord().ToString();// 记录总数
    this.Page_Count().ToString();//分页总数   

    Init_Brower();//初始化浏览
   }
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.first.ServerClick += new System.EventHandler(this.first_ServerClick);
   this.prior.ServerClick += new System.EventHandler(this.prior_ServerClick);
   this.next.ServerClick += new System.EventHandler(this.next_ServerClick);
   this.last.ServerClick += new System.EventHandler(this.last_ServerClick);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion                
  
       
  /// <summary>
  /// 显示数据
  /// </summary>
  protected void ShowData()
  {
   DataSet ds = new DataSet();//数据集
   ASWBLM.Include.UnionInfo_Provider _uip = new ASWBLM.Include.UnionInfo_Provider();
   string vSQL = "";
   vSQL = GetSQLCommond(vSQL,startID,endID);
   
   ds = _uip.ShowAllUnionInfo(vSQL);//取得全部数据的数据集

   try
   { 
    Response.Write("<p align=center>");   
    foreach(DataRow dr in ds.Tables["Table"].Rows)
    {       
     Response.Write("<tr align = center onmouseover = /"this.bgColor = '#cccccc'/" onmouseout = /"this.bgColor='';/">");
     
     Response.Write("<td align=/"left/" width=/"60%/"><font color=/"#00309C/">");
     Response.Write("<a href=/"UnionInfo_Read.aspx?id="+dr["Id"].ToString()+"/" target=/"_self/">");     
     Response.Write(dr["Title"].ToString());

     Response.Write("</a>");
     Response.Write("</td>");

     Response.Write("<td align=/"right/">");
     Response.Write("<font color=/"#999999/">");
     Response.Write("( "+dr["SummaryDateTime"].ToString()+" )");
     Response.Write("     ( 已阅读"+dr["ReadTimes"].ToString()+"次 )");
     Response.Write("</font>");
     Response.Write("</td>");

     Response.Write("</tr>");
    }                
    Response.Write("</p>");
    startID = ds.Tables["Table"].Rows[0].ItemArray[0].ToString();       //通过数组,取第一个数据,得到开始号“startID”
    RowCount = ds.Tables["Table"].DefaultView.Count;//得到表的行数
    endID = ds.Tables["Table"].Rows[RowCount-1].ItemArray[0].ToString();//通过数组,取最后一个数据,得到结束号“endID”
   }
   catch(SqlException e)
   {     
    Response.Write(e.Message);
   }
  }


  /// <summary>
  /// 计算未显示记录数
  /// </summary>
  /// <returns></returns>
  protected void NotShownRecords()
  {
   not_shown_records = this.CountRecord()/*查询总记录数*/ - (CurrentPage/*当前页*/ - 1) * page_count/*每页记录数*/;
  }


  /// <summary>
  /// 进行输出信息
  /// </summary>
  protected  void PageLoad_Count()
  {
   this.NotShownRecords();
   Response.Write("总共"+this.CountRecord()+"条记录       ");
   Response.Write("共有"+this.Page_Count()+"页       ");
   Response.Write("第"+CurrentPage.ToString()+"页       ");
   Response.Write("本页共有"+RowCount.ToString()+"条记录       ");
  }

 

  /// <summary>
  /// 获得总记录总数
  /// </summary>
  /// <returns>时间条件范围内记录总数intCount</returns>
  protected int CountRecord()
  {   
   int intCount = 0;
   SqlConnection SqlCon = new SqlConnection(Common._DBConnStr);
   SqlCon.Open ();
   
   //找到条件范围内的记录总数
   string strCount = "select count(*) from UnionInfo";
   
   //找到符合条件的第一个记录
   //string strNum = "select top 1 Id from UnionInfo";

   SqlCommand MyComm = new SqlCommand(strCount,SqlCon);
   SqlDataReader dr = MyComm.ExecuteReader();//读取数据流
   if(dr.Read())
   {
                intCount = Int32.Parse(dr[0].ToString());
   }
   else
   {
               intCount = 0;
   }
   dr.Close();
   SqlCon.Close();              
   return intCount;
  }


  /// <summary>
  /// 总分页数
  /// </summary>
  /// <returns>分页总数</returns>
  protected int Page_Count()
  {
   int pageSum = 0;//分页总数   
   pageSum = this.CountRecord() / page_count;           ///记录总数/分页的页数
   if ((this.CountRecord() % page_count) > 0) pageSum++;   
   return pageSum;
  }


  /// <summary>
  /// 取得SQL语句
  /// </summary>
  /// <param name="vCmd">返回命令行</param>
  /// <returns></returns>
  private string GetSQLCommond(string vCommond,string startID,string endID)
  {
   this.NotShownRecords();//执行未显示的行

   vCommond = "SELECT TOP "+page_count+"  {0},{1},{2},{3}  FROM [UnionInfo]";
   
   if(IsPrior)//判断“上一页”
   {
    
   }
 
   if(IsNext)//判断“下一页”
   {

   }

   if (IsLast)//判断“最后一页”
   {

   }

   vCommond = string.Format(vCommond,"Id","Title","SummaryDateTime","ReadTimes");//这个是数据表的字段
   return vCommond;
  }


  /// <summary>
  /// 输入按钮的状态,进行是否可用
  /// </summary>
  /// <param name="first">第一页的状态</param>
  /// <param name="prior">上一页的状态</param>
  /// <param name="next1">下一页的状态</param>
  /// <param name="last">最后一页的状态</param>
  protected void SetButtonState(bool first_,bool prior_,bool next_,bool last_)
  {
   if (CurrentPage==1)//到“第一页”
   {
    first.Disabled = true;//第一页状态
    prior.Disabled = true;//上一页状态
    next.Disabled = false;   //下一页状态
    last.Disabled = false; //最后一页状态
   }
   else if (CurrentPage==this.Page_Count())//到“最后一页”
   {
    first.Disabled = false;//第一页状态
    prior.Disabled = false;//上一页状态
    next.Disabled = true;   //下一页状态
    last.Disabled = true; //最后一页状态
   }
   else
   {
    first.Disabled = first_;//第一页状态
    prior.Disabled = prior_;//上一页状态
    next.Disabled = next_;   //下一页状态
    last.Disabled = last_; //最后一页状态
   }
  }

 

  /// <summary>
  /// 第一页按钮
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void first_ServerClick(object sender, System.EventArgs e)
  {            
   CurrentPage  = 1;
   this.SetButtonState(true,true,false,false); 
   startID = "";
   endID = "";
   RowCount = '0';
   IsLast = false;
   IsPrior = false;
   IsNext = false;
  }


  /// <summary>
  /// 上一页按钮
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void prior_ServerClick(object sender, System.EventArgs e)
  {
   if( CurrentPage == 1)//判断“当前页”是否为1
   {
    this.SetButtonState(true,true,false,false);
   }
   else
   {
    CurrentPage=CurrentPage - 1;//“当前页”自减
    this.SetButtonState(false,false,false,false);
   }
   IsPrior = true;
   IsNext = false;
   IsLast = false;  
  }


  /// <summary>
  /// 最后一页
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void last_ServerClick(object sender, System.EventArgs e)
  {        
   CurrentPage=this.Page_Count();//到最后一页
   this.SetButtonState(false,false,true,true);
   IsLast = true;
   IsPrior = false;
   IsNext = false;
  }


  /// <summary>
  /// 下一页
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void next_ServerClick(object sender, System.EventArgs e)
  {                      
   if(CurrentPage == this.Page_Count())//判断“当前页”是否为“分页总数”
   {
    this.SetButtonState(false,false,true,true);
   }
   else
   {
    CurrentPage=CurrentPage + 1;//“当前页”自加
    this.SetButtonState(false,false,false,false);
   }
   IsNext = true; 
   IsLast = false;
   IsPrior = false;
  }


  /// <summary>
  /// 初始浏览按钮
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void Init_Brower()
  {
   CurrentPage = 1;//肯定是从第一页开始
   if ((CurrentPage == 1) && (this.Page_Count() == 1))
   {
    first.Disabled = true;//第一页状态
    prior.Disabled = true;//上一页状态
    next.Disabled = true;//下一页状态
    last.Disabled = true; //最后一页状态
   }
   else
   {
    first.Disabled = true;//第一页状态
    prior.Disabled = true;//上一页状态
    next.Disabled = false;//下一页状态
    last.Disabled = false; //最后一页状态
   }
   startID = "";//开始号
   endID = "";//结束号  
   IsLast = false;
   IsPrior = false;
   IsNext = false;
  }
 }
}

本文没有列出SQL语句,是希望我和我的好朋友们的劳动成果已经用于商业用途了,还有就是希望各位自己动手写写,应该没有问题的了

 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值