산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

MySQL 연결 기능이 있는 Python:커넥터, 데이터베이스 생성, 테이블, 삽입 [예제]

Python과 MySQL 연결을 사용하려면 SQL에 대한 지식이 있어야 합니다.

자세히 알아보기 전에 이해합시다

MySQL이란 무엇입니까?

MySQL은 오픈 소스 데이터베이스이며 최고의 RDBMS(관계형 데이터베이스 관리 시스템) 유형 중 하나입니다. MySQLdb의 공동 설립자는 Michael Widenius의 이름이며 MySQL 이름은 Michael의 딸에서 따온 것입니다.

이 튜토리얼에서 배우게 될 것입니다

Windows, Linux/Unix에 MySQL 커넥터 Python을 설치하는 방법

Linux/Unix에 MySQL 설치:

공식 사이트에서 Linux/Unix용 RPM 패키지 다운로드:https://www.mysql.com/downloads/

터미널에서 다음 명령을 사용하십시오.

rpm  -i <Package_name>
Example   rpm -i MySQL-5.0.9.0.i386.rpm

Linux 체크인

mysql --version

Windows에 MySQL 설치

공식 사이트에서 MySQL 데이터베이스 exe를 다운로드하고 Windows에서 일반적인 소프트웨어 설치와 같이 설치합니다. 단계별 가이드는 이 자습서를 참조하십시오.

Python용 MySQL 커넥터 라이브러리 설치 방법

MySQL을 Python과 연결하는 방법은 다음과 같습니다.

Python 2.7 이하의 경우 다음과 같이 pip를 사용하여 설치합니다.

pip install mysql-connector

Python 3 이상 버전의 경우 다음과 같이 pip3을 사용하여 설치합니다.

pip3 install mysql-connector 

Python으로 MySQL 데이터베이스 연결 테스트

여기에서 Python에서 MySQL 데이터베이스 연결을 테스트하기 위해 사전 설치된 MySQL 커넥터를 사용하고 자격 증명을 connect()에 전달합니다. 아래 Python MySQL 커넥터 예제와 같이 호스트, 사용자 이름 및 비밀번호와 같은 기능.

Python으로 MySQL에 액세스하는 구문:

import mysql.connector
	db_connection = mysql.connector.connect(
  	host="hostname",
  	user="username",
  	passwd="password"
    )

:

import mysql.connector
db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root"
)
print(db_connection)

출력 :

<mysql.connector.connection.MySQLConnection object at 0x000002338A4C6B00>

여기 출력은 성공적으로 생성된 연결을 보여줍니다.

Python을 사용하여 MySQL에서 데이터베이스 생성

SQL에서 새 데이터베이스를 만드는 구문은

CREATE DATABASE "database_name"

이제 Python에서 데이터베이스 프로그래밍을 사용하여 데이터베이스를 생성합니다.

import mysql.connector
  db_connection = mysql.connector.connect(
  host= "localhost",
  user= "root",
  passwd= "root"
  )
# creating database_cursor to perform SQL operation
db_cursor = db_connection.cursor()
# executing cursor with execute method and pass SQL query
db_cursor.execute("CREATE DATABASE my_first_db")
# get list of all databases
db_cursor.execute("SHOW DATABASES")
#print all databases
for db in db_cursor:
	print(db)

출력 :

위 이미지는 my_first_db를 보여줍니다. 데이터베이스가 생성되었습니다

Python을 사용하여 MySQL에서 테이블 만들기

아래 MySQL 커넥터 Python 예제와 같이 두 개의 열이 있는 간단한 "student" 테이블을 만들어 보겠습니다.

SQL 구문 :

CREATE  TABLE student (id INT, name VARCHAR(255))

예:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
#Here creating database table as student'
db_cursor.execute("CREATE TABLE student (id INT, name VARCHAR(255))")
#Get database table'
db_cursor.execute("SHOW TABLES")
for table in db_cursor:
	print(table)

출력 :

 ('student',) 

기본 키로 테이블 생성

직원을 만들어 보겠습니다. 세 개의 다른 열이 있는 테이블. id에 기본 키를 추가합니다. 데이터베이스 연결이 있는 아래 Python 프로젝트에 표시된 대로 AUTO_INCREMENT 제약 조건이 있는 열입니다.

SQL 구문 :

CREATE TABLE employee(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), salary INT(6))

:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
#Here creating database table as employee with primary key
db_cursor.execute("CREATE TABLE employee(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), salary INT(6))")
#Get database table
db_cursor.execute("SHOW TABLES")
for table in db_cursor:
	print(table)

출력 :

('employee',) ('student',)

Python을 사용하는 MySQL의 ALTER 테이블

Alter 명령은 SQL에서 테이블 구조를 수정하는 데 사용됩니다. 여기에서 학생 을 변경합니다. 테이블을 만들고 id에 기본 키를 추가합니다. 아래 Python MySQL 커넥터 프로젝트와 같은 필드입니다.

SQL 구문 :

ALTER TABLE student MODIFY id INT PRIMARY KEY

:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
#Here we modify existing column id
db_cursor.execute("ALTER TABLE student MODIFY id INT PRIMARY KEY")

출력 :

여기 아래에서 id 를 볼 수 있습니다. 열이 수정되었습니다.

Python에서 MySQL을 사용한 삽입 작업:

이미 생성한 MySQL Database 테이블에 삽입 작업을 수행해 보겠습니다. STUDENT 테이블과 EMPLOYEE 테이블에 데이터를 삽입합니다.

SQL 구문 :

INSERT INTO student (id, name) VALUES (01, "John")
INSERT INTO employee (id, name, salary) VALUES(01, "John", 10000)

:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
student_sql_query = "INSERT INTO student(id,name) VALUES(01, 'John')"
employee_sql_query = " INSERT INTO employee (id, name, salary) VALUES (01, 'John', 10000)"
#Execute cursor and pass query as well as student data
db_cursor.execute(student_sql_query)
#Execute cursor and pass query of employee and data of employee
	db_cursor.execute(employee_sql_query)
db_connection.commit()
print(db_cursor.rowcount, "Record Inserted")

출력 :

 2 Record Inserted 

python

  1. EXAMPLE이 있는 Python String strip() 함수
  2. 예제가 있는 Python 문자열 count()
  3. Python String format() 예제로 설명
  4. 예제가 있는 Python 문자열 find() 메서드
  5. 예제가 있는 Python Lambda 함수
  6. 예제가 있는 Python round() 함수
  7. 예제가 있는 Python map() 함수
  8. 예제가 있는 Python Timeit()
  9. 예제가 있는 컬렉션의 Python 카운터
  10. 예제가 있는 Python의 type() 및 isinstance()