I can not connect to the database using nuxt js and mssql
my error:
Database connection failed: sql.connect is not a functionat connectToDatabase (serverdbindex.ts:21:24)at sqlQuery (serverdbindex.ts:38:24)at blogModel.read (servermodelblog.ts:31:10)at Object.read (servercontrollerblog.ts:7:1)
//my index.ts
import * as sql from 'mssql';
const config = {
user: 'myuser', // Your database username
password: 'mypassword', // Your database password
server: 'mydatabase.database.windows.net', // Server name for Azure SQL Database
database: 'mydb', // Your database name
options: {
encrypt: true, // Use encryption
enableArithAbort: true // Enable ArithAbort
}
};
let pool: sql.ConnectionPool | null = null;
export const connectToDatabase = async (): Promise<sql.ConnectionPool> => {
try {
if (!pool) {
pool = await sql.connect(config);
console.log('Connected to SQL Server database');
}
return pool;
} catch (err) {
console.error('Database connection failed:', err);
throw err;
}
};
interface QueryOptions {
query: string;
values?: any[];
}
export const sqlQuery = async ({ query, values }: QueryOptions): Promise<any[]> => {
try {
const pool = await connectToDatabase();
const request = pool.request();
if (values) {
values.forEach((value, index) => {
request.input(`param${index + 1}`, value);
});
}
const result = await request.query(query.replace(/?/g, (match, i) => `@param${i + 1}`));
return result.recordset;
} catch (err) {
console.error('SQL query error:', err);
throw err;
}
// blog.ts (server/model/blog.ts)
import { sqlQuery } from '~~/server/db/index';
interface Blog {
id?: number;
title: string;
content: string;
}
export const create = async (blog: Blog): Promise<number> => {
const query = `
INSERT INTO Blogs (title, content)
VALUES (?, ?)
SELECT SCOPE_IDENTITY() AS id
`;
const result = await sqlQuery({
query,
values: [blog.title, blog.content]
});
return result[0].id;
};
export const read = async (): Promise<Blog[]> => {
const query = `
SELECT id, title, content
FROM Blogs
`;
return sqlQuery({ query });
};
export const detail = async (id: string): Promise<Blog> => {
const query = `
SELECT id, title, content
FROM Blogs
WHERE id = ?
`;
const result = await sqlQuery({ query, values: [id] });
return result[0];
};
export const update = async (id: string, blog: Blog): Promise<void> => {
const query = `
UPDATE Blogs
SET title = ?, content = ?
WHERE id = ?
`;
await sqlQuery({ query, values: [blog.title, blog.content, id] });
};
export const remove = async (id: string): Promise<void> => {
const query = `
DELETE FROM Blogs
WHERE id = ?
`;
await sqlQuery({ query, values: [id] });
};
What is wrong? Please help. I do not know what to do. I imported mssql with yarn.
I excepted to make basic crud app with nuxt and mssql. And it not working.
New contributor
Metrind is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.