How i can insert a new data to DB?

Hey, im using D1 CLI and Worker, i want to fetch a data, wait to data, and insert the data to D1. How i can do it?

something like that?

		if (pathname === '/api/update-database') {
			const newData = await getData();
			for (const data of newData) {
				if (!data.id || !data.fullName) {
					// Skip clubs with missing data
					continue;
				}

				console.log('data', data);
				const info = await env.DB
					.prepare('INSERT INTO Clubs (Id, FullName) VALUES (?1, ?2)')
					.bind(club.id, club.fullName)
					.run();

				console.log(info);
			}

			return new Response('Database updated');
		}

I tried deployed the code above to the worker, enter to the pathname, see the response ā€˜Database updatedā€™, and enter to the DB dashboard to see the new data, but when im enter to the DB tables, nothing changeā€¦

You are using club here, but data everywhere else.

	if (pathname === '/api/update-database') {
		const newData = await getData();
		for (const data of newData) {
			if (!data.id || !data.fullName) {
				// Skip clubs with missing data
				continue;
			}

			console.log('data', data);
			const info = await env.DB
				.prepare('INSERT INTO Clubs (Id, FullName) VALUES (?1, ?2)')
				.bind(data.id, data.fullName)
				.run();

			console.log(info);
		}

		return new Response('Database updated');
	}

Sorry, wrong editing, fix my example, but still, the code dont work and the DB dont updateā€¦

const newData = [
        {id: 1233, fullName: 'something'},
        {id: 1234, fullName: 'seomthing else'},
      ]

Using the above in place of getData() I see the information successfully inserted into the DB.

I suggest using a try...catch block

// rest of code
try {
  await env.DB
    .prepare('INSERT INTO Clubs (Id, FullName) VALUES (?1, ?2)')
    .bind(data.id, data.fullName)
    .run();
}  catch(err) {
  console.log(err)
}
// rest of code
1 Like

Oh, its catch the error:

Error: D1_TYPE_ERROR: Type 'undefined' not supported for value 'undefined'
    at D1PreparedStatement.bind (worker.js:13783:17)
    at Object.fetch (worker.js:13612:86)
    at async jsonError (worker.js:13641:12) {
  stack: Error: D1_TYPE_ERROR: Type 'undefined' not supportā€¦2:86)
    at async jsonError (worker.js:13641:12),
  message: D1_TYPE_ERROR: Type 'undefined' not supported for value 'undefined',
  cause: Error: Type 'undefined' not supported for value 'undefined'
    at D1PreparedStatement.bind (workerā€¦
}

As per D1 Error list documentation

Returned when there is a mismatch in the type between a column and a value. A common cause is supplying an undefined variable (unsupported) instead of null

1 Like