c#ip地址生成器到SQL

时间:2011-08-21 23:36:48

标签: c# python sql tsql

我在互联网上找到了以下python代码,我想在SQL数据库中创建一个包含每个ipv4地址的表。我不在python中编码,而是我发现的。

我的问题是 1:我可以使用T-SQL代码生成表吗? (一栏即0.0.0.0-255.255.255.255)

2:我将如何在c#中做到这一点?使用最快的方法吗?我知道显示结果会使控制台应用程序减慢400%

#!/usr/bin/env python
def generate_every_ip_address():
    for octet_1 in range( 256 ):
    for octet_2 in range( 256 ):
    for octet_3 in range( 256 ):
    for octet_4 in range( 256 ):
        yield "%d.%d.%d.%d" % (octet_1, octet_2, octet_3, octet_4)

for ip_address in generate_every_ip_address():
    print ip_address

3 个答案:

答案 0 :(得分:0)

这会有用吗?

DECLARE @a INTEGER
DECLARE @b INTEGER
DECLARE @c INTEGER
DECLARE @d INTEGER
DECLARE @IPADDRESS nvarchar(50)

set @a = 0

WHILE @a < 256
BEGIN
    SET @b = 0
    WHILE @b < 256
    BEGIN
        SET @c = 0
        WHILE @c < 256
        BEGIN
            SET @d = 0
            WHILE @d < 256
            BEGIN
                SET @IPADDRESS = CAST(@a AS nvarchar(3)) + '.' + CAST(@b AS nvarchar(3)) + '.' + CAST(@c AS nvarchar(3)) + '.' + CAST(@d AS nvarchar(3))
                PRINT @IPADDRESS
                SET @d = @d + 1
            END
            SET @c = @c + 1
        END
        SET @b = @b + 1
    END
    SET @a = @a + 1
END

答案 1 :(得分:0)

使用以下TSQL批量插入16,581,375行将非常简单。

DECLARE @Counter INT
SET @Counter = 0
SET NOCOUNT ON ;

WHILE ( @Counter <= 255 ) 
    BEGIN
        RAISERROR('Procesing %d' ,0,1,@Counter) WITH NOWAIT ;

        WITH    Numbers ( N )
                  AS ( SELECT   CAST(number AS VARCHAR(3))
                       FROM     master.dbo.spt_values
                       WHERE    type = 'P'
                                AND number BETWEEN 0 AND 255
                     )
            INSERT  INTO YourTable
                    ( IPAddress
                    )
                    SELECT  @Counter + '.' + N1.N + '.' + N2.N + '.' + N3.N
                    FROM    Numbers N1 ,
                            Numbers N2 ,
                            Numbers N3 


        SET @Counter = @Counter + 1
    END

答案 2 :(得分:0)

请使用int IDENTITY列存储每个IP地址。它们只有32位。用你正在存储的任何东西填满你的桌子。