Back

Reading and Writing Data Using the Microsoft SQL Server API

Aug 8, 20245 minute read

Hey there, fellow JavaScript devs! Ready to dive into the world of Microsoft SQL Server API? Let's talk about syncing data for user-facing integrations. Buckle up, because we're about to make your life a whole lot easier.

Setting the Stage

First things first, let's get our environment set up. You'll need to install the mssql package:

npm install mssql

Now, let's configure our connection:

const sql = require('mssql'); const config = { user: 'your_username', password: 'your_password', server: 'your_server', database: 'your_database' }; sql.connect(config).then(() => { console.log('Connected to SQL Server'); }).catch(err => { console.error('Connection error:', err); });

Reading Data: It's Query Time!

Let's fetch some user data:

async function getUserData(userId) { try { const result = await sql.query`SELECT * FROM Users WHERE id = ${userId}`; return result.recordset[0]; } catch (err) { console.error('Query error:', err); } }

Writing Data: Update Those Preferences

Updating user preferences? No sweat:

async function updateUserPreferences(userId, preferences) { try { await sql.query`UPDATE Users SET preferences = ${JSON.stringify(preferences)} WHERE id = ${userId}`; console.log('Preferences updated successfully'); } catch (err) { console.error('Update error:', err); } }

Sync Like a Pro

Here's a basic sync function to get you started:

async function syncUserData(localData, remoteData) { const updates = []; for (const localUser of localData) { const remoteUser = remoteData.find(u => u.id === localUser.id); if (!remoteUser || localUser.lastModified > remoteUser.lastModified) { updates.push(localUser); } } // Batch update if (updates.length > 0) { const table = new sql.Table('Users'); table.create = false; table.columns.add('id', sql.Int, {primary: true}); table.columns.add('name', sql.NVarChar(50)); table.columns.add('preferences', sql.NVarChar(sql.MAX)); table.columns.add('lastModified', sql.DateTime); updates.forEach(user => { table.rows.add(user.id, user.name, JSON.stringify(user.preferences), user.lastModified); }); const request = new sql.Request(); await request.bulk(table); console.log(`${updates.length} users synced successfully`); } }

Performance Boost: Stored Procedures

Want to kick it up a notch? Use stored procedures:

async function getUserDataSP(userId) { try { const request = new sql.Request(); request.input('userId', sql.Int, userId); const result = await request.execute('sp_GetUserData'); return result.recordset[0]; } catch (err) { console.error('Stored procedure error:', err); } }

Keep It Safe: Parameterized Queries

Always use parameterized queries to prevent SQL injection:

async function safeUpdateUser(userId, name) { try { await sql.query`UPDATE Users SET name = ${name} WHERE id = ${userId}`; console.log('User updated safely'); } catch (err) { console.error('Safe update error:', err); } }

Wrapping Up

There you have it! You're now equipped to read and write data like a boss using the Microsoft SQL Server API. Remember to always validate your data, handle errors gracefully, and keep security in mind.

Happy coding, and may your queries be ever efficient!