在使用Node.js向MySQL中插入Orders表和Order Items表时,可以按照以下步骤进行操作:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'your_database_name'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ' + err.stack);
return;
}
console.log('Connected to MySQL database as id ' + connection.threadId);
});
const createOrdersTableQuery = `
CREATE TABLE Orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(255),
order_date DATE
)
`;
const createOrderItemsTableQuery = `
CREATE TABLE OrderItems (
id INT AUTO_INCREMENT PRIMARY KEY,
order_id INT,
product_name VARCHAR(255),
quantity INT,
FOREIGN KEY (order_id) REFERENCES Orders(id)
)
`;
connection.query(createOrdersTableQuery, (err, results) => {
if (err) {
console.error('Error creating Orders table: ' + err.stack);
return;
}
console.log('Orders table created successfully');
});
connection.query(createOrderItemsTableQuery, (err, results) => {
if (err) {
console.error('Error creating OrderItems table: ' + err.stack);
return;
}
console.log('OrderItems table created successfully');
});
const insertOrderQuery = `
INSERT INTO Orders (customer_name, order_date)
VALUES ('John Doe', '2022-01-01')
`;
const insertOrderItemsQuery = `
INSERT INTO OrderItems (order_id, product_name, quantity)
VALUES (1, 'Product A', 2)
`;
connection.query(insertOrderQuery, (err, results) => {
if (err) {
console.error('Error inserting data into Orders table: ' + err.stack);
return;
}
console.log('Data inserted into Orders table successfully');
});
connection.query(insertOrderItemsQuery, (err, results) => {
if (err) {
console.error('Error inserting data into OrderItems table: ' + err.stack);
return;
}
console.log('Data inserted into OrderItems table successfully');
});
connection.end((err) => {
if (err) {
console.error('Error closing MySQL connection: ' + err.stack);
return;
}
console.log('MySQL connection closed');
});
以上是使用Node.js在MySQL中插入Orders表和Order Items表的基本步骤。根据实际需求,可以根据表结构和数据进行适当的调整和修改。
领取专属 10元无门槛券
手把手带您无忧上云