프로젝트

Flutter-PostgresSQL 연동하기

Multitab 2022. 10. 10. 21:28

와! Flutter와 로컬 PostgresSQL과 연동에 성공했다. Dart언어에 Postgres 라이브러리를 이용했다

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:postgres/postgres.dart';

void main() {
  runApp(const MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State createState() => _State();
}

class _State extends State<MyApp> {
  var connection;

  String rowVal = "";
  int count = 0;
  String inputText = "";

  _State(){
    connectDB();
  }

  Future<void> connectDB() async{
    if(connection.isClosed){
      return;
    }
    connection = PostgreSQLConnection(
        "10.0.2.2",
        5432,
        "postgres",
        username: "multitab",
        password: "1234",
    );
    await connection.open();
    print("Database is Connected");
  }

  void ListName() async{
    List<List<dynamic>> results = await connection.query("SELECT * FROM \"TestScheme\".\"TestTable\" LIMIT 1000");
    for (final row in results){
      rowVal = row[0];
      print(rowVal);
    }
  }

  void putData() async{
    await connectDB();
    if(inputText != ""){
      await connection.query("INSERT INTO \"TestScheme\".\"TestTable\" (\"Name\") VALUES ('$inputText');");
      print("Insert Complete");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("일리소프트 출근부"),
      ),
      body: Center(
        child: Column(
          children: [
            TextButton(
              onPressed: () => {
                putData()
              },
              child: Text('Button Clicks $rowVal'),
            ),
            TextField(
              onChanged: (text){
                setState(() {
                  inputText = text;
                });
              }
            )
          ]),
      ),
    );
  }
}

근데 티스토리 코드블럭에 Dart 지원이 안되네..? 이건 예상 못했다.. 분발하자 티스토리.. 분발하자 구글..

'프로젝트' 카테고리의 다른 글

Unity - Azure Kinect 연동하기  (0) 2022.11.22
Unity3D - Leapmotion 연동하기  (0) 2022.11.21
Flutter를 해보자  (0) 2022.10.09
제1회 SW-Up 경진대회 참가  (0) 2021.01.31