- MySQL 基础
- MySQL - 首页
- MySQL - 简介
- MySQL - 特性
- MySQL - 版本
- MySQL - 变量
- MySQL - 安装
- MySQL - 管理
- MySQL - PHP 语法
- MySQL - Node.js 语法
- MySQL - Java 语法
- MySQL - Python 语法
- MySQL - 连接
- MySQL - Workbench
- MySQL 数据库
- MySQL - 创建数据库
- MySQL - 删除数据库
- MySQL - 选择数据库
- MySQL - 显示数据库
- MySQL - 复制数据库
- MySQL - 数据库导出
- MySQL - 数据库导入
- MySQL - 数据库信息
- MySQL 用户
- MySQL - 创建用户
- MySQL - 删除用户
- MySQL - 显示用户
- MySQL - 修改密码
- MySQL - 授予权限
- MySQL - 显示权限
- MySQL - 收回权限
- MySQL - 锁定用户账户
- MySQL - 解锁用户账户
- MySQL 表
- MySQL - 创建表
- MySQL - 显示表
- MySQL - 修改表
- MySQL - 重命名表
- MySQL - 克隆表
- MySQL - 截断表
- MySQL - 临时表
- MySQL - 修复表
- MySQL - 描述表
- MySQL - 添加/删除列
- MySQL - 显示列
- MySQL - 重命名列
- MySQL - 表锁定
- MySQL - 删除表
- MySQL - 派生表
- MySQL 查询
- MySQL - 查询
- MySQL - 约束
- MySQL - 插入查询
- MySQL - 选择查询
- MySQL - 更新查询
- MySQL - 删除查询
- MySQL - 替换查询
- MySQL - 插入忽略
- MySQL - 插入重复键更新
- MySQL - 插入到选择
- MySQL 运算符和子句
- MySQL - Where 子句
- MySQL - Limit 子句
- MySQL - Distinct 子句
- MySQL - Order By 子句
- MySQL - Group By 子句
- MySQL - Having 子句
- MySQL - AND 运算符
- MySQL - OR 运算符
- MySQL - Like 运算符
- MySQL - IN 运算符
- MySQL - ANY 运算符
- MySQL - EXISTS 运算符
- MySQL - NOT 运算符
- MySQL - 不等于运算符
- MySQL - IS NULL 运算符
- MySQL - IS NOT NULL 运算符
- MySQL - Between 运算符
- MySQL - UNION 运算符
- MySQL - UNION 与 UNION ALL
- MySQL - MINUS 运算符
- MySQL - INTERSECT 运算符
- MySQL - INTERVAL 运算符
- MySQL 连接
- MySQL - 使用连接
- MySQL - 内连接
- MySQL - 左连接
- MySQL - 右连接
- MySQL - 交叉连接
- MySQL - 全连接
- MySQL - 自连接
- MySQL - 删除连接
- MySQL - 更新连接
- MySQL - Union 与 Join
- MySQL 触发器
- MySQL - 触发器
- MySQL - 创建触发器
- MySQL - 显示触发器
- MySQL - 删除触发器
- MySQL - 插入前触发器
- MySQL - 插入后触发器
- MySQL - 更新前触发器
- MySQL - 更新后触发器
- MySQL - 删除前触发器
- MySQL - 删除后触发器
- MySQL 数据类型
- MySQL - 数据类型
- MySQL - VARCHAR
- MySQL - BOOLEAN
- MySQL - ENUM
- MySQL - DECIMAL
- MySQL - INT
- MySQL - FLOAT
- MySQL - BIT
- MySQL - TINYINT
- MySQL - BLOB
- MySQL - SET
- MySQL 正则表达式
- MySQL - 正则表达式
- MySQL - RLIKE 运算符
- MySQL - NOT LIKE 运算符
- MySQL - NOT REGEXP 运算符
- MySQL - regexp_instr() 函数
- MySQL - regexp_like() 函数
- MySQL - regexp_replace() 函数
- MySQL - regexp_substr() 函数
- MySQL 函数和运算符
- MySQL - 日期和时间函数
- MySQL - 算术运算符
- MySQL - 数值函数
- MySQL - 字符串函数
- MySQL - 聚合函数
- MySQL 杂项概念
- MySQL - NULL 值
- MySQL - 事务
- MySQL - 使用序列
- MySQL - 处理重复项
- MySQL - SQL 注入
- MySQL - 子查询
- MySQL - 注释
- MySQL - 检查约束
- MySQL - 存储引擎
- MySQL - 将表导出到 CSV 文件
- MySQL - 将 CSV 文件导入数据库
- MySQL - UUID
- MySQL - 公共表表达式
- MySQL - On Delete Cascade
- MySQL - Upsert
- MySQL - 水平分区
- MySQL - 垂直分区
- MySQL - 游标
- MySQL - 存储函数
- MySQL - Signal
- MySQL - Resignal
- MySQL - 字符集
- MySQL - 校对
- MySQL - 通配符
- MySQL - 别名
- MySQL - ROLLUP
- MySQL - 今天日期
- MySQL - 字面量
- MySQL - 存储过程
- MySQL - Explain
- MySQL - JSON
- MySQL - 标准差
- MySQL - 查找重复记录
- MySQL - 删除重复记录
- MySQL - 选择随机记录
- MySQL - 显示 Processlist
- MySQL - 更改列类型
- MySQL - 重置自动递增
- MySQL - Coalesce() 函数
- MySQL 有用资源
- MySQL - 有用函数
- MySQL - 语句参考
- MySQL - 快速指南
- MySQL - 有用资源
- MySQL - 讨论
MySQL - 将CSV导入数据库
将 MySQL CSV 导入数据库
要将 MySQL 数据从 CSV 文件导入数据库表,我们可以使用 MySQL 的 LOAD DATA INFILE 语句。
在将 CSV 文件导入数据库服务器之前,我们必须确保以下事项 -
- 数据库表 - 确保您已设置了一个数据库表来接收传入的数据。
- CSV 文件 - 您需要一个包含要导入数据的 CSV 文件。
- 用户权限 - 确保您的帐户具有执行此操作的必要权限,特别是 FILE 和 INSERT 权限。
- 匹配列 - 目标表和 CSV 文件应具有匹配的列,并且数据类型相同。
- CSV 格式 - CSV 文件应采用逗号分隔格式,每行表示一条记录。
语法
以下是 MySQL 中 LOAD DATA INFILE 语句的语法 -
LOAD DATA INFILE file_path INTO TABLE table_name FIELDS TERMINATED BY delimiter ENCLOSED BY enclosure LINES TERMINATED BY line_separator IGNORE number_of_lines_to_skip;
其中,
file_path 是包含要导入数据的 CSV 文件的路径。
table_name 是目标表的名称,数据将导入到其中。
delimiter 是 CSV 文件中分隔每个记录的字符。
Enclosure 是 CSV 文件中包含字符串记录的字符。
line_seperator 是 CSV 文件中标记行尾的字符。
number_of_lines_to_skip 是 CSV 文件开头要忽略的行数。
示例
首先,让我们使用以下查询创建一个名为 EMPLOYEES 的表 -
CREATE TABLE EMPLOYEES( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25) NOT NULL, SALARY DECIMAL(18, 2), PRIMARY KEY(ID) );
现在,让我们向上面创建的表中插入行 -
INSERT INTO EMPLOYEES VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ), (2, 'Khilan', 25, 'Delhi', 1500.00 ), (3, 'kaushik', 23, 'Kota', 2000.00 ), (4, 'Chaitali', 25, 'Mumbai', 6500.00 ), (5, 'Hardik', 27, 'Bhopal', 8500.00 ), (6, 'Komal', 22, 'MP', 4500.00 ), (7, 'Muffy', 24, 'Indore', 10000.00 );
获得的 EMPLOYEES 表如下所示 -
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
2 | Khilan | 25 | Delhi | 1500.00 |
3 | Kaushik | 23 | Kota | 2000.00 |
4 | Chaitali | 25 | Mumbai | 6500.00 |
5 | Hardik | 27 | Bhopal | 8500.00 |
6 | Komal | 22 | MP | 4500.00 |
7 | Muffy | 24 | Indore | 10000.00 |
导出数据到 CSV -
现在,我们使用以下查询将 EMPLOYEES 表中的数据导出到名为“EMPLOYEES_BACKUP”的 CSV 文件中 -
SELECT * FROM EMPLOYEES INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEES_BACKUP.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\r\n';
执行上述查询后,将在指定路径创建 CSV 格式文件。以下是执行上述查询后获得的输出 -
Query OK, 7 rows affected (0.00 sec)
当我们打开“EMPLOYEES_BACKUP.csv”文件时,以下是获得的图像 -
创建另一个表 -
现在,让我们创建一个名为 “CUSTOMERS” 的表,其列和数据类型与 EMPLOYEES 表相同 -
CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25) NOT NULL, SALARY DECIMAL(18, 2), PRIMARY KEY(ID) );
以下是上述代码的输出 -
Query OK, 0 rows affected (0.03 sec)
从 CSV 导入数据 -
现在,我们使用以下查询将“EMPLOYEES_BACKUP.csv”文件中的所有数据导入到 CUSTOMERS 表中 -
LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEES_BACKUP.csv' INTO TABLE CUSTOMERS FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n';
获得的结果如下 -
Query OK, 7 rows affected (0.01 sec) Records: 7 Deleted: 0 Skipped: 0 Warnings: 0
验证数据导入 -
要验证数据是否已成功导入到 CUSTOMERS 表中,我们可以使用以下 SELECT 语句 -
SELECT * FROM CUSTOMERS;
正如我们在下面的输出中看到的,CUSTOMERS 表包含与 EMPLOYEES 表相同的数据,因为 CSV 数据已成功导入 -
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
2 | Khilan | 25 | Delhi | 1500.00 |
3 | Kaushik | 23 | Kota | 2000.00 |
4 | Chaitali | 25 | Mumbai | 6500.00 |
5 | Hardik | 27 | Bhopal | 8500.00 |
6 | Komal | 22 | MP | 4500.00 |
7 | Muffy | 24 | Indore | 10000.00 |
使用客户端程序导入 CSV 文件
我们还可以使用客户端程序将 CSV 文件导入数据库。
语法
要通过 PHP 程序将 CSV 文件导入数据库,我们需要使用 mysqli 函数 query() 执行“LOAD DATA INFILE”语句,如下所示 -
$sql = "LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEES_BACKUP.csv' INTO TABLE CUSTOMERS FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '' LINES TERMINATED BY '\n'"; $mysqli->query($sql);
要通过 JavaScript 程序将 CSV 文件导入数据库,我们需要使用 mysql2 库的 query() 函数执行“LOAD DATA INFILE”语句,如下所示 -
sql = `LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEES_BACKUP.csv' INTO TABLE CUSTOMERS FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '' LINES TERMINATED BY '\n'`; con.query(sql);
要通过 Java 程序将 CSV 文件导入数据库,我们需要使用 JDBC 函数 execute() 执行“LOAD DATA INFILE”语句,如下所示 -
String sql = "LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEES_BACKUP.csv' INTO TABLE CUSTOMERS FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '' LINES TERMINATED BY '\\n'"; statement.execute(sql);
要通过 Python 程序将 CSV 文件导入数据库,我们需要使用 MySQL Connector/Python 的 execute() 函数执行“LOAD DATA INFILE”语句,如下所示 -
import_sql = "LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEE_BACKUP.csv' INTO TABLE CUSTOMERS FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\r\n'" cursorObj.execute(import_sql)
示例
以下是程序 -
$dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $db = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db); if ($mysqli->connect_errno) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf('Connected successfully.
'); $sql = "CREATE TABLE EMPLOYEES( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25) NOT NULL, SALARY DECIMAL(18, 2), PRIMARY KEY(ID) )"; if($mysqli->query($sql)){ printf("Employees table created successfully...!\n"); } //now lets insert some data into it.. $sql = "INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 )"; if($mysqli->query($sql)){ printf("First record inserted successfully...!\n"); } $sql = "INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 )"; if($mysqli->query($sql)){ printf("Second record inserted successfully...!\n"); } $sql = "INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'kaushik', 23, 'Kota', 2000.00 )"; if($mysqli->query($sql)){ printf("Third record inserted successfully...!\n"); } //display table record $sql = "SELECT * FROM EMPLOYEES"; if($result = $mysqli->query($sql)){ printf("Table records: \n"); while($row = mysqli_fetch_array($result)){ printf("ID: %d, NAME: %s, AGE: %d, ADDRESS: %s, SALARY: %f", $row['ID'], $row['NAME'], $row['AGE'], $row['ADDRESS'], $row['SALARY']); printf("\n"); } } //now let's export the table data into csv file $sql = "SELECT ID, NAME, AGE, ADDRESS, SALARY FROM EMPLOYEES INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEES_BACKUP.csv' FIELDS ENCLOSED BY '' TERMINATED BY ';' ESCAPED BY '' LINES TERMINATED BY '\r\n'"; if($result = $mysqli->query($sql)){ printf("Table data exported successfully....!\n"); print_r($result , "\n"); } //now let's create a customers table $sql = "CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25) NOT NULL, SALARY DECIMAL(18, 2), PRIMARY KEY(ID) )"; if($mysqli->query($sql)){ printf("Customers table created successfully...!\n"); } //now lets import employees table data csv file into customers table $sql = "LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEES_BACKUP.csv' INTO TABLE CUSTOMERS FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '' LINES TERMINATED BY '\n'"; if($mysqli->query($sql)){ printf("CSV file data imported successfully into Customers table....!\n"); } //print customers table records $sql = "SELECT * FROM CUSTOMERS"; if($result = $mysqli->query($sql)){ printf("Customers table records after importing csv file data into it: \n"); while($row = mysqli_fetch_array($result)){ printf("ID: %d, NAME: %s, AGE: %d, ADDRESS: %s, SALARY: %f", $row['ID'], $row['NAME'], $row['AGE'], $row['ADDRESS'], $row['SALARY']); printf("\n"); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();
输出
获得的输出如下所示 -
Employees table created successfully...! First record inserted successfully...! Second record inserted successfully...! Third record inserted successfully...! Table records: ID: 1, NAME: Ramesh, AGE: 32, ADDRESS: Ahmedabad, SALARY: 2000.000000 ID: 2, NAME: Khilan, AGE: 25, ADDRESS: Delhi, SALARY: 1500.000000 ID: 3, NAME: kaushik, AGE: 23, ADDRESS: Kota, SALARY: 2000.000000 Table data exported successfully....! Customers table created successfully...! CSV file data imported successfully into Customers table....! Customers table records after importing csv file data into it: ID: 1, NAME: Ramesh, AGE: 32, ADDRESS: Ahmedabad, SALARY: 2000.000000 ID: 2, NAME: Khilan, AGE: 25, ADDRESS: Delhi, SALARY: 1500.000000 ID: 3, NAME: kaushik, AGE: 23, ADDRESS: Kota, SALARY: 2000.000000
var mysql = require('mysql2'); var con = mysql.createConnection({ host:"localhost", user:"root", password:"password" }); //Connecting to MySQL con.connect(function(err) { if (err) throw err; // console.log("Connected successfully...!"); // console.log("--------------------------"); sql = "USE TUTORIALS"; con.query(sql); //create employees table sql = "CREATE TABLE EMPLOYEES( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25) NOT NULL, SALARY DECIMAL(18, 2), PRIMARY KEY(ID) )"; if(con.query(sql)){ console.log("Employees table created successfully...!"); } //now let's insert some values sql = `INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 )`; if(con.query(sql)){ console.log("First record inserted successfully...!"); } sql = `INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 )`; if(con.query(sql)){ console.log("Second record inserted successfully...!"); } sql = `INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'kaushik', 23, 'Kota', 2000.00 )`; if(con.query(sql)){ console.log("Third record inserted successfully...!"); } sql = "SELECT * FROM EMPLOYEES"; con.query(sql, function(err, result){ console.log("Employees table records: "); if (err) throw err; console.log(result); }); sql = `SELECT ID, NAME, AGE, ADDRESS, SALARY FROM EMPLOYEES INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEES_BACKUP.csv' FIELDS ENCLOSED BY '' TERMINATED BY ';' ESCAPED BY '' LINES TERMINATED BY '\r\n'`; con.query(sql, function(err, result){ if (err) throw err; console.log("Table data exported successfully....!"); }); sql = `CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25) NOT NULL, SALARY DECIMAL(18, 2), PRIMARY KEY(ID) )`; con.query(sql, function(err, result){ if (err) throw err; console.log("Customers table created successfully...!"); }); sql = `LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEES_BACKUP.csv' INTO TABLE CUSTOMERS FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '' LINES TERMINATED BY '\n'`; con.query(sql, function(err, result){ if (err) throw err; console.log("CSV file data imported successfully into Customers table....!"); }); sql = "SELECT * FROM CUSTOMERS"; con.query(sql, function(err, result){ console.log("Customers table records after importing csv file data into it: ") if (err) throw err; console.log(result); }); });
输出
获得的输出如下所示 -
Employees table created successfully...! First record inserted successfully...! Second record inserted successfully...! Third record inserted successfully...! Employees table records: [ { ID: 1, NAME: 'Ramesh', AGE: 32, ADDRESS: 'Ahmedabad', SALARY: '2000.00' }, { ID: 2, NAME: 'Khilan', AGE: 25, ADDRESS: 'Delhi', SALARY: '1500.00' }, { ID: 3, NAME: 'kaushik', AGE: 23, ADDRESS: 'Kota', SALARY: '2000.00' } ] Table data exported successfully....! Customers table created successfully...! CSV file data imported successfully into Customers table....! Customers table records after importing csv file data into it: [ { ID: 1, NAME: 'Ramesh', AGE: 32, ADDRESS: 'Ahmedabad', SALARY: '2000.00' }, { ID: 2, NAME: 'Khilan', AGE: 25, ADDRESS: 'Delhi', SALARY: '1500.00' }, { ID: 3, NAME: 'kaushik', AGE: 23, ADDRESS: 'Kota', SALARY: '2000.00' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ImportCSVToDatabase { public static void main(String[] args) { String url = "jdbc:mysql://127.0.0.1:3306/TUTORIALS"; String user = "root"; String password = "password"; ResultSet rs; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, password); Statement st = con.createStatement(); //System.out.println("Database connected successfully...!"); String sql = "CREATE TABLE EMPLOYEES( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25) NOT NULL, SALARY DECIMAL(18, 2), PRIMARY KEY(ID))"; st.execute(sql); System.out.println("Table EMPLOYEES created successfully....!"); //let's insert some records into it... String sql1 = "INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ), (2, 'Khilan', 25, 'Delhi', 1500.00 ), (3, 'kaushik', 23, 'Kota', 2000.00 )"; st.execute(sql1); System.out.println("Records inserted successfully...!"); //lets print table records String sql2 = "SELECT * FROM EMPLOYEES"; rs = st.executeQuery(sql2); System.out.println("Table records: "); while(rs.next()) { String id = rs.getString("id"); String name = rs.getString("name"); String age = rs.getString("age"); String address = rs.getString("address"); String salary = rs.getString("salary"); System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Address: " + address + ", Salary: " + salary); } //lets export the table records into csv file String sql3 = "SELECT ID, NAME, AGE, ADDRESS, SALARY FROM EMPLOYEES INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEES_BACKUP.csv' FIELDS ENCLOSED BY '' TERMINATED BY ';' ESCAPED BY '' LINES TERMINATED BY '\\r\\n'"; st.execute(sql3); System.out.println("Table records exported successfully into CSV file....!"); //let's create one more table name Customers; String sql4 = "CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25) NOT NULL, SALARY DECIMAL(18, 2), PRIMARY KEY(ID))"; st.execute(sql4); System.out.println("Table Customers created successfully...!"); //lets import csv file into database String sql5 = "LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEES_BACKUP.csv' INTO TABLE CUSTOMERS FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '' LINES TERMINATED BY '\\n'"; st.execute(sql5); System.out.println("Data imported successfully...!"); //now lets print customers table records String sql6 = "SELECT * FROM CUSTOMERS"; rs = st.executeQuery(sql6); System.out.println("Table records: "); while(rs.next()) { String id = rs.getString("id"); String name = rs.getString("name"); String age = rs.getString("age"); String address = rs.getString("address"); String salary = rs.getString("salary"); System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Address: " + address + ", Salary: " + salary); } }catch(Exception e) { e.printStackTrace(); } } }
输出
获得的输出如下所示 -
Table EMPLOYEES created successfully....! Records inserted successfully...! Table records: Id: 1, Name: Ramesh, Age: 32, Address: Ahmedabad, Salary: 2000.00 Id: 2, Name: Khilan, Age: 25, Address: Delhi, Salary: 1500.00 Id: 3, Name: kaushik, Age: 23, Address: Kota, Salary: 2000.00 Table records exported successfully into CSV file....! Table Customers created successfully...! Data imported successfully...! Table records: Id: 1, Name: Ramesh, Age: 32, Address: Ahmedabad, Salary: 2000.00 Id: 2, Name: Khilan, Age: 25, Address: Delhi, Salary: 1500.00 Id: 3, Name: kaushik, Age: 23, Address: Kota, Salary: 2000.00
import mysql.connector # Establishing the connection connection = mysql.connector.connect( host='localhost', user='root', password='password', database='tut' ) # Creating a cursor object cursorObj = connection.cursor() # Creating the table 'EMPLOYEES' create_table_query = ''' CREATE TABLE EMPLOYEES( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25) NOT NULL, SALARY DECIMAL(18, 2), PRIMARY KEY(ID) ); ''' cursorObj.execute(create_table_query) print("Table 'EMPLOYEES' is created successfully!") # Inserting records into 'EMPLOYEES' table sql = "INSERT INTO EMPLOYEES (ID, NAME, AGE, ADDRESS, SALARY) VALUES (%s, %s, %s, %s, %s);" values = [ (1, 'Ramesh', 32, 'Ahmedabad', 2000.00), (2, 'Khilan', 25, 'Delhi', 1500.00), (3, 'Kaushik', 23, 'Kota', 2000.00), (4, 'Chaitali', 25, 'Mumbai', 6500.00), (5, 'Hardik', 27, 'Bhopal', 8500.00), (6, 'Komal', 22, 'MP', 4500.00), (7, 'Muffy', 24, 'Indore', 10000.00) ] cursorObj.executemany(sql, values) print("Data inserted into the 'EMPLOYEES' table.") # Export the table data into a CSV file export_sql = """ SELECT ID, NAME, AGE, ADDRESS, SALARY FROM EMPLOYEES INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEE_BACKUP.csv' FIELDS ENCLOSED BY '"' TERMINATED BY ',' ESCAPED BY '"' LINES TERMINATED BY '\r\n'; """ cursorObj.execute(export_sql) print("Table data exported successfully!") # Now let's create a 'CUSTOMERS' table create_another_table = ''' CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25) NOT NULL, SALARY DECIMAL(18, 2), PRIMARY KEY(ID) ); ''' cursorObj.execute(create_another_table) print("Table 'CUSTOMERS' is created successfully!") # Now let's import 'EMPLOYEES' table data from the CSV file into 'CUSTOMERS' table import_sql = """ LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/EMPLOYEE_BACKUP.csv' INTO TABLE CUSTOMERS FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\r\n' """ cursorObj.execute(import_sql) print("CSV file data imported successfully into Customers table....!\n") # Print 'CUSTOMERS' table records cursorObj.execute("SELECT * FROM CUSTOMERS") records = cursorObj.fetchall() # Printing the records print("Customers table records after importing CSV file data into it: \n") for record in records: print(record) # Closing the cursor and connection cursorObj.close() connection.close()
输出
获得的输出如下所示 -
Table 'EMPLOYEES' is created successfully! Data inserted into the 'EMPLOYEES' table. Table data exported successfully! Table 'CUSTOMERS' is created successfully! CSV file data imported successfully into Customers table...! Customers table records after importing CSV file data into it: (1, 'Ramesh', 32, 'Ahmedabad', Decimal('2000.00')) (2, 'Khilan', 25, 'Delhi', Decimal('1500.00')) (3, 'Kaushik', 23, 'Kota', Decimal('2000.00')) (4, 'Chaitali', 25, 'Mumbai', Decimal('6500.00')) (5, 'Hardik', 27, 'Bhopal', Decimal('8500.00')) (6, 'Komal', 22, 'MP', Decimal('4500.00')) (7, 'Muffy', 24, 'Indore', Decimal('10000.00'))