You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node新手使用Node查询MySQL时遇ER_BAD_DB_ERROR错误求助

Hey there! Let's work through this MySQL error you're facing in your Node.js code—super common issue when starting out, so no worries.

First, let's break down the error

The core problem here is the ER_BAD_DB_ERROR with the message Unknown database '201803028'. This means MySQL can't find a database named 201803028 on your local server. Also, there's a secondary issue in your SQL query that we'll fix too.

Step 1: Create the missing database

  1. Open your terminal and log into MySQL using your root credentials:
    mysql -u root -p
    
    When prompted, enter your password (123456).
  2. Check what databases exist on your server:
    SHOW DATABASES;
    
    Look for 201803028 in the list—if it's not there, create it:
    CREATE DATABASE 201803028;
    
  3. Verify it was created by running SHOW DATABASES; again, then exit MySQL with EXIT;.

Step 2: Fix the table name in your SQL query

Your table name user-table uses a hyphen, which MySQL interprets as a subtraction operator instead of part of the table name. You need to wrap it in backticks to tell MySQL it's a single identifier. Also, you had a typo in your error log (console.log('err', e... should be err instead of e). Here's the corrected code snippet:

const mysql = require('mysql'); 
var db = mysql.createConnection({ 
  host:'localhost', 
  user:'root', 
  password:'123456', 
  database:'201803028'
}); 

// Add a connection check to catch early issues
db.connect((err) => {
  if (err) {
    console.error('Failed to connect to database:', err);
    return;
  }
  console.log('Successfully connected to MySQL!');
});

db.query('SELECT * FROM `user-table`;',(err,data)=>{ 
  if(err){ 
    console.log('Query error:', err); 
  } else {
    console.log('Query results:', data);
  }
  // Close the connection after the query (good practice)
  db.end();
});

Quick extra tip

Always add error handling for the connection step—it helps you catch issues like wrong passwords or unavailable servers before even running your query.

内容的提问来源于stack exchange,提问作者Sylvia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:26:02