3
Answers

React Native Login connect with sql server ?

I created a Login application that connects to the sql server using Visual Studio Code. The Login and SignUp application logs into the sql server to read the Table 'TABUSERNAME' and export it to the grid, but I get an error, my computer's sql server information:

user: 'sa'
pass: 'Coffee'
server:'MICROSOFT' or '192.168.1.100'
database: 'Cafe'

Can you please fix my code errors ?

File: App.js

Answers (3)

1
Photo of Tuhin Paul
39 34.6k 314.3k 1y
  1. Connection String:
    • Double-check the format and values of your connection string, ensuring they align with your SQL Server configuration.
    • Verify server name, instance name (if applicable), database name, authentication mode, and credentials.
  2. Credentials:
    • Confirm that you're using the correct username and password for the SQL Server account.
  3. Database Server Accessibility:
    • Ensure your application can reach the SQL Server instance on the specified network address or server name.
    • Check for firewall restrictions or network connectivity issues.
  4. Table Name:

    Verify that the table name 'TABUSERNAME' is spelled correctly and exists in the 'Cafe' database.

    pen_spark

1
Photo of Jayraj Chhaya
298 6k 96.3k 1y

Share error details so we can understand the problem and find the solution for it.

0
Photo of Dong Lam Trien
721 986 160.9k 1y

I posted a previous post and couldn't send the code, so this page reported an error so I resubmitted it

 When it's running, I enter user and password and press the login button, I get an error: ERROR Cannot convert null value to object

//App.js
import React, { useState } from 'react';
import { StyleSheet, View, TextInput, Button, FlatList, Text } from 'react-native';
import SQLite from 'react-native-sqlite-storage';
//import axios from 'axios';

const App = () => {
  // Kh?i t?o state s? luu tr? thông tin ngu?i dùng
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');  
  const [sqliteData, setSqliteData] = useState([]); // Thêm 'sqliteData' vào danh sách các state


  // Hàm x? lý khi ngu?i dùng nh?n nút Login
  const handleLogin = async () => {
    //alert('login');
    //console.log('login1');
    try {
      // K?t n?i b?ng co s? d? li?u
      const db = SQLite.openDatabase(
        {          
          name: 'Cafe.db',
          location: 'default',
          //createFromLocation: '~www/test.db',
        },
        () => {
          console.log('Connected to the database.');
        },
        (error) => {
          console.error('Failed to connect to the database.', error);
        }
      );
            
      // Th?c hi?n truy v?n SQL s? lây d? li?u t? b?ng
      db.transaction(tx => {
        tx.executeSql(
          'SELECT * FROM TABUSERNAME',
          [],
          (_, result) => {
            if (result.rows) {
              const rows = result.rows.raw();
              setSqliteData(rows); // Luu tr? d? li?u t? SQLite vào state 'sqliteData'
            } else {
              console.log('No rows returned from the query.');
            }
          },
          error => {
            console.error('Failed to execute query.', error);
          }
        );
      });
      
      // Ðóng k?t n?i co s? d? li?u khi không s? d?ng n?a
      //return () => {
      db.close();
      console.log('Database connection closed.');
      //};

    } catch (error) {
      console.error(error.message);
    }
  };

   
  // Hàm x? lý khi ngu?i dùng nh?n nút Signup
  const handleSignup = async () => {
    try {
      //
    } catch (error) {
      console.error(error.message);
    }
  };
  

  return (
    <View style={styles.container}>
      
      <View style={styles.flatlist}>
        {/* Hi?n th? d? li?u trong ô lu?i */}
        <FlatList
          data={sqliteData}
          renderItem={({ item }) => <Text>{JSON.stringify(item)}</Text>}
          keyExtractor={(_, index) => index.toString()}
        />
      </View>
      
      <View style={styles.inputText}>
        <View style={styles.text}>
         <View style={styles.user}>
         {/* ngu?i dùng nh?p tên ngu?i dùng */}
            <TextInput placeholder="Username" onChangeText={setUsername} />
         </View>
         <View style={styles.pass}>
            {/* ngu?i dùng nh?p m?t kh?u */}
            <TextInput placeholder="Password" onChangeText={setPassword} secureTextEntry={true} />
         </View>
        </View>



        <View style={styles.button}>
          <View style={styles.login}>
              {/* Nút s? th?c hi?n ch?c nang dang nh?p */}
              <Button title="Login" onPress={handleLogin} />
          </View>
          <View style={styles.signup}>
              {/* Nút s? th?c hi?n ch?c nang dang ký */}
              <Button title="Signup" onPress={handleSignup} />
          </View>
        </View>
      </View>
         

      
    </View>
  );
};

export default App;


const styles = StyleSheet.create({
  container: {
    flex : 1,
    backgroundColor : '#e7feff',      

  },
  flatlist: {
    //top : 340,
    //width : 50,
    //height : 50,
    backgroundColor : 'red',
  },
  inputText : {
    top: 340,    
    
  },
  text : {
    marginLeft : 30,
  },
  
  button : {
    width : 360,
    height : 150,
    marginHorizontal : 20,
    justifyContent : 'center',

  },
  login : {
    
  },

  signup : {
    top : 20,  
    },

  })
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const sql = require('mssql');

const app = express();
const port = 3000;

app.use(bodyParser.json());

const config = {
  user: 'sa',
  password: '123456',
  server: 'MICROSOFT',
  database: 'Cafe',
  options: {
        encrypt: false // N?u không s? d?ng k?t n?i b?o m?t, d?t encrypt là false
      }
};

app.post('/login', async (req, res) => {
  const { username, password } = req.body;

  try {
      await sql.connect(dbConfig);

      const query = `SELECT * FROM TABUSERNAME WHERE USERNAME = @username AND PASSWORDS = @password`;
      const request = new sql.Request();
      request.input('username', sql.VarChar, username);
      request.input('password', sql.VarChar, password);
      
      const result = await request.query(query);

      if (result.recordset.length > 0) {
          res.json({ success: true, message: 'Login successful' });
      } else {
          res.status(401).json({ success: false, message: 'Login failed' });
      }
  } catch (err) {
      console.error('Database connection error', err);
      res.status(500).json({ success: false, message: 'Internal server error' });
  } finally {
      sql.close();
  }
});

/*
app.post('/login', async (req, res) => {
  try {
    await sql.connect(config);
    const result = await sql.query(`SELECT * FROM TABUSERNAME WHERE USERNAME='${req.body.username}' AND PASSWORDS='${req.body.password}'`);
    sql.close();
    res.json(result.recordset);
  } catch (error) {
    res.status(500).send(error.message);
  }
});
*/


app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});