Home > Software design >  I am not able to save data in MariaDB database
I am not able to save data in MariaDB database

Time:09-11

when I try to insert into MariaDB database with following code.

const insertQuery = `INSERT INTO profiles (profile_name, profile_url, job_title, company_name, company_link, search_term) VALUES ? `;
  const values = data.map((profile) => [
    profile.profileName,
    profile.profileUrl,
    profile.jobTitle,
    profile.companyName,
    profile.companyLink,
    keyword,
  ]);
  console.log(values);
  const response = await connection
    .execute(insertQuery, [values])
    .catch((err) => {
      throw new Error("Error while inserting into database: "   err);
    });

Code throws this error.

Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1

My Syntax is ok I have cross-checked and I have seen similar queries on StackOverflow and Implemented them. Moreover,I have implemented solution mentioned here.

My solution is the same as they have But I don't know why it's not working. My data object looks like this.

const data = [
    {
      profileName: "test",
      profileUrl:
        "https://www.linkedin.com/in/ACwAABxSfpQBV-1eqHmBUOLk7MoOfIj8s9_pmjI",
      jobTitle: "test",
      companyName: "test",
      companyLink: "test",
    },
    {
      profileName: "test",
      profileUrl:
        "https://www.linkedin.com/in/ACwAABxSfpQBV-1eqHmBUOLk7MoOfIj8s9_pmjI",
      jobTitle: "test",
      companyName: "test",
      companyLink: "test",
    },
  ]

where am I making mistake?

system info:

Server version: 5.5.5-10.3.34-MariaDB-0ubuntu0.20.04.1 Ubuntu 20.04
mysql2: ^2.3.3
node: v14.19.3

CodePudding user response:

This syntax is wrong:

INSERT INTO profiles (profile_name, profile_url, 
  job_title, company_name, company_link, search_term) 
VALUES ? 

When you use a VALUES clause, you must put parentheses around the tuple of values, and you must have one placeholder for each column named in the column list.

Example:

INSERT INTO profiles (profile_name, profile_url, 
  job_title, company_name, company_link, search_term) 
VALUES (?, ?, ?, ?, ?, ?)

MySQL and MariaDB also support a (nonstandard) alternative INSERT syntax that makes it more clear how to match the columns and placeholders:

INSERT INTO profiles SET profile_name=?, profile_url=?, 
  job_title=?, company_name=?, company_link=?, search_term=?;

CodePudding user response:

You have values not one value.

  INSERT INTO profiles (profile_name, profile_url, job_title, company_name, company_link, search_term) VALUES (?,?,?,?,?,?)

https://mariadb.com/kb/en/insert/

  • Related