如何合并对象值并验证CSV文件名对应SQL表是否存在?
Hey there! Let's break this down simply so you can easily check if your target table exists in the database. You're already halfway there with the steps you've taken—let's connect the dots.
First, Let's Recap Your Progress
You already:
- Got the CSV filename without the
.csvsuffix (e.g.,fxbewertung) - Fetched the full list of tables from your
dateindatabase - Started looping through the table results
Solution 1: Use Array Methods to Compare (Easy to Understand)
Instead of looping to get single-element arrays, we can convert the database's table list into a plain array of table names, then check if your target name is in that list.
Here's how to update your code:
connection.query('Show tables from datein', function(err, datein) { if (err) { console.error('Oops, error getting tables:', err); return; } // Step 1: Turn the database result into a simple array of table names const allTableNames = datein.map(tableObj => tableObj.Tables_in_datein); // Now allTableNames looks like: ['fxbewertung', 'kontoauszug', 'lsreport'] // Step 2: Get your target table name from the CSV (your existing code) const filename = filePath.slice(51); const richtigername = filename.replace(".csv","").toString(); // Step 3: Check if the target name is in the array const doesTableExist = allTableNames.includes(richtigername); // Now you have a true/false value to use! console.log(`Table "${richtigername}" exists: ${doesTableExist}`); });
What's happening here?
map()goes through each object in the database result and pulls out only the table name (theTables_in_dateinvalue)includes()checks if your target name is present in the array of table names, returningtrueorfalsedirectly
Solution 2: Use SQL's IF EXISTS Directly (More Efficient)
If you want to skip fetching all tables and let the database do the work, you can run a dedicated query to check for the table. This is better if you have lots of tables:
// Get your target table name first (your existing code) const filename = filePath.slice(51); const richtigername = filename.replace(".csv","").toString(); // SQL query to check table existence const checkQuery = `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_schema = 'datein' AND table_name = ?)`; connection.query(checkQuery, [richtigername], function(err, result) { if (err) { console.error('Error checking table:', err); return; } // Extract the true/false result from the query const existsValue = result[0][Object.keys(result[0])[0]]; const doesTableExist = existsValue === 1; console.log(`Table "${richtigername}" exists: ${doesTableExist}`); });
Why this works:
- The SQL query asks the database "does this table exist?" and returns
1(yes) or0(no) - We just convert that 1/0 to a
true/falsevalue for your code to use
Either method will give you the true or false result you need. Start with Solution 1 if you want something straightforward to follow!
内容的提问来源于stack exchange,提问作者Frederic

