1

我创建了一个表来存储 IP 地址。

CREATE TABLE ipdetails( ip_address DECIMAL(16,4) NOT NULL, vlan_id varchar(50) );

但是当我尝试插入表格时,它给了我一个错误:

INSERT INTO ipdetails VALUES (192.169.165.128, 'Sample1')

无论如何我可以在 SQL 表中存储一个带有很多小数位的数字,如果是这样,我应该使用什么数据类型?请指教。

提前致谢!

4

3 回答 3

5

你有几个选择:

  • 将其存储为 VARCHAR。IP 地址实际上并不是一个您可能会对其进行数学运算的数字,那么为什么要以数字格式存储它呢?
  • 将其以十六进制形式存储为单个数字。虽然您不能真正以十进制执行此操作,但在十六进制中,IP 是一个 8 位数字。
  • 将其存储为(最多)四个单独的字段。可能没有必要,但对于某些应用程序(您可能希望主要只关注 IP 的一部分),这可能很有用。
于 2013-02-21T03:44:20.587 回答
2

您可以将 IP 存储为数字,这就是它们在内部存在的方式,但您必须编写代码来来回转换:

#include <arpa/inet.h>
/* 
 * Returns a pointer to an internal array containing the string, which is overwritten with each call to the function.
 * You need to copy the string if you want to keep the value returned.
 */
extern char *inet_ntoa (struct in_addr in);

/* 
 * Convert Internet host address from numbers-and-dots notation in CP
 * into binary data and store the result in the structure inp.
 */
extern int inet_aton (const char *cp, struct in_addr *inp);

这是一些简单的 SQL,它使用 127.0.0.1 执行其中一个执行 ip->decimal 的操作

SELECT
TO_NUMBER(REGEXP_SUBSTR('127.0.0.1','\w+',1,1))*POWER(2,24)
+ TO_NUMBER(REGEXP_SUBSTR('127.0.0.1','\w+',1,2))*POWER(2,16)
+ TO_NUMBER(REGEXP_SUBSTR('127.0.0.1','\w+',1,3))*POWER(2,8)
+ TO_NUMBER(REGEXP_SUBSTR('127.0.0.1','\w+',1,4))*POWER(2,0) IP
FROM
DUAL;
于 2013-02-21T03:49:13.983 回答
1

尝试将值存储为字符串并使用引号:

CREATE TABLE ipdetails( ip_address varchar(15) NOT NULL, vlan_id varchar(50) );

进而 。. .

INSERT INTO ipdetails VALUES ('192.169.698.365', 'Sample1')

您可能希望将每个组件存储在单独的字段中。

于 2013-02-21T03:44:35.247 回答