LOAD DATA INFILE / PHP MySQLi / 为输入的数据添加额外的列/值处理 NULL 值

发布于 2024-12-27 06:55:13 字数 261 浏览 3 评论 0原文

我一直在尝试 LOAD DATA INFILE,并且我希望能够做一些事情。我不确定它们是否可能,或者我是否需要创建一个临时表来上传。

当 CSV 文件上传/输入到我的应用程序中时,我希望有一个自动递增的行列。此外,我想向每一行添加一个列值,以标识上传文件的用户。

我在 InnoDB 数据库上使用 PHP/MySQLi。

我的 CSV 文件中也可能有空字符串作为空值。有没有一种简单的方法将这些值作为 NULL 输入到数据库中?

感谢您的帮助!

I have been experimenting with LOAD DATA INFILE and there are a couple things I would like to be able to do. I'm not sure if they are possible, or if I may need to create a temporary table for the upload.

When a CSV file is uploaded/inputed in my application, I'd like to have an auto-incrementing column for the rows. In addition, I'd like to add a column value to each row identifying the user who uploaded the file.

I am using PHP/MySQLi on a InnoDB database.

I may also have empty strings for null values in my CSV files. Is there a simple way to input these values as NULL into the database?

Thanks for all your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

粉红×色少女 2025-01-03 06:55:13

为了实现您想要的目的,您需要先以编程方式预先创建表以及触发器函数,然后再将数据加载到表中。

因此,首先使用触发器创建表:

示例:

 CREATE TABLE foo (
    id INT NOT NULL AUTO_INCREMENT,
    fooitems TEXT,
    PRIMARY KEY (id)
 );

 CREATE TRIGGER fooblank2null
 BEFORE INSERT ON foo
 FOR EACH ROW
 SET NEW.fooitems=IF(TRIM(NEW.fooitems)='',NULL,NEW.fooitems);

测试触发器是否有效:

 INSERT INTO foo (fooitems)
 VALUES
 ('i'),(''),('am'),('foo'),(' '),('.');

您现在可以将数据加载到特定列。

例子:

 LOAD DATA
 INFILE 'foo.txt'
 INTO TABLE foo
 FIELDS TERMINATED BY ',' ENCLOSED BY '"'
 LINES TERMINATED BY '\n'
 (fooitems);

to achieve what you want, you would need to programmatically pre-create the table first along with a triggers function prior to loading data into it.

therefore, create the table first with triggers:

example:

 CREATE TABLE foo (
    id INT NOT NULL AUTO_INCREMENT,
    fooitems TEXT,
    PRIMARY KEY (id)
 );

 CREATE TRIGGER fooblank2null
 BEFORE INSERT ON foo
 FOR EACH ROW
 SET NEW.fooitems=IF(TRIM(NEW.fooitems)='',NULL,NEW.fooitems);

to test if the trigger works:

 INSERT INTO foo (fooitems)
 VALUES
 ('i'),(''),('am'),('foo'),(' '),('.');

you can now load the data to the specific column.

example:

 LOAD DATA
 INFILE 'foo.txt'
 INTO TABLE foo
 FIELDS TERMINATED BY ',' ENCLOSED BY '"'
 LINES TERMINATED BY '\n'
 (fooitems);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文