Cannot connect to MS-SQL with react-native

Viewed 2192

I have used the following package import MSSQL from 'react-native-mssql';

near the above package on hover, it shows Could not find a declaration file for module 'react-native-mssql'. 'd:/React Native Apps/Login/node_modules/react-native-mssql/index.android.js' implicitly has an 'any' type. Try npm install @types/react-native-mssql if it exists or add a new declaration (.d.ts) file containing declare module 'react-native-mssql'; module "d:/React Native Apps/Login/node_modules/react-native-mssql/index.android

I have tried installing as mentioned above but nothing works.

And in code, I am getting an error at below line. MSSQL.connect(config);

error is following undeined is not an object (evaluating '_reactNativeMssql2.default.connect')

Please tell me how do I connect to MSSQL with react-native.

2 Answers

react-native-mssql can be installed with npm install --save react-native-mssql

then edit file android/settings.gradle and add:

include ':react-native-mssql'
project(':react-native-mssql').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-mssql/android')

as well as file android/app/build.gradle:

dependencies {
    ...
    implementation project(':react-native-mssql')
}

then it can be added to the packages list:

...
import com.stonem.mssql.MSSQLPackage;

...
@Override
protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
        ...
        .addPackage(new MSSQLPackage())
        ...
    );
}

and then connected:

import MSSQL from 'react-native-mssql';
...

let config = {
    server: '192.168.1.1', // ip address of the mssql database
    username: 'sa',        // username to login to the database
    password: 'password',  // password to login to the database
    database: 'admin',     // the name of the database to connect to
    port: 1234             // OPTIONAL, port of the database on the server
}
MSSQL.connect(config);

an example for a SELECT query:

let query = 'SELECT TOP * FROM USERS'
MSSQL.executeQuery(query);

and one for an UPDATE query:

let query = 'UPDATE USERS SET Active=0'
MSSQL.executeUpdate(query);

make sure to call MSSQL.close(); once the connection isn't required anymore.

You could use "react-native link react-native-mssql" in the command prompt after using "cd Project_Name" to fix the issue, if 'Could not find a declaration file for module 'react-native-mssql' was your issue all along.

Related