Python에서 열 이름을 사용하여 SQL 결과 열 값을 검색하는 방법은 무엇입니까?
Python에서 Column Index 대신 Column name을 사용하여 SQL result column 값을 검색할 수 있는 방법이 있습니까?MySQL에서 Python 3를 사용하고 있습니다.제가 찾고 있는 구문은 Java 구성과 거의 비슷합니다.
Object id = rs.get("CUSTOMER_ID");
열이 꽤 많은 테이블이 있는데 액세스해야 하는 각 열에 대해 인덱스를 계속 작성해야 하는 것은 정말 힘든 일입니다.게다가 인덱스는 내 코드를 읽기 어렵게 만든다.
감사합니다!
MySQLdb 모듈에는 다음과 같은DictCursor가 있습니다.
다음과 같이 사용합니다(Python DB-API를 사용한 MySQL 스크립트 작성).
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT name, category FROM animal")
result_set = cursor.fetchall()
for row in result_set:
print "%s, %s" % (row["name"], row["category"])
edit: 사용자 1305650에 따르면 이 방법도 유효합니다.
이 게시물은 오래되었지만 검색을 통해 표시될 수 있습니다.
이제 mysql.discl을 사용하여 다음과 같이 사전을 검색할 수 있습니다.https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html
mysql 사이트의 예를 다음에 나타냅니다.
cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")
print("Countries in Europe:")
for row in cursor:
print("* {Name}".format(Name=row['Name']))
커서 사전이라는 것을 찾아야 합니다.
mysql 커넥터를 사용하고 있으며 이 파라미터를 커서에 추가해야 합니다.그래서 인덱스 대신 컬럼 이름을 사용할 수 있습니다.
db = mysql.connector.connect(
host=db_info['mysql_host'],
user=db_info['mysql_user'],
passwd=db_info['mysql_password'],
database=db_info['mysql_db'])
cur = db.cursor()
cur = db.cursor( buffered=True , dictionary=True)
Import pymysql
# Open database connection
db = pymysql.connect("localhost","root","","gkdemo1")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT * from user")
# Get the fields name (only once!)
field_name = [field[0] for field in cursor.description]
# Fetch a single row using fetchone() method.
values = cursor.fetchone()
# create the row dictionary to be able to call row['login']
**row = dict(zip(field_name, values))**
# print the dictionary
print(row)
# print specific field
print(**row['login']**)
# print all field
for key in row:
print(**key," = ",row[key]**)
# close database connection
db.close()
import mysql
import mysql.connector
db = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "P@ssword1",
database = "appbase"
)
cursor = db.cursor(dictionary=True)
sql = "select Id, Email from appuser limit 0,1"
cursor.execute(sql)
result = cursor.fetchone()
print(result)
# output => {'Id': 1, 'Email': 'me@gmail.com'}
print(result["Id"])
# output => 1
print(result["Email"])
# output => me@gmail.com
python 2.7
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='password', db='sakila')
cur = conn.cursor()
n = cur.execute('select * from actor')
c = cur.fetchall()
for i in c:
print i[1]
물론 있죠.Python 2.7.2+에서는...
import MySQLdb as mdb
con = mdb.connect('localhost', 'user', 'password', 'db');
cur = con.cursor()
cur.execute('SELECT Foo, Bar FROM Table')
for i in range(int(cur.numrows)):
foo, bar = cur.fetchone()
print 'foo = %s' % foo
print 'bar = %s' % bar
특정 열에서 값 선택:
import pymysql
db = pymysql.connect("localhost","root","root","school")
cursor=db.cursor()
sql="""select Total from student"""
l=[]
try:
#query execution
cursor.execute(sql)
#fetch all rows
rs = cursor.fetchall()
#iterate through rows
for i in rs:
#converting set to list
k=list(i)
#taking the first element from the list and append it to the list
l.append(k[0])
db.commit()
except:
db.rollback()
db.close()
print(l)
자세한 내용은 제공하지 않았지만 다음과 같은 방법을 시도해 볼 수 있습니다.
# conn is an ODBC connection to the DB
dbCursor = conn.cursor()
sql = ('select field1, field2 from table')
dbCursor = conn.cursor()
dbCursor.execute(sql)
for row in dbCursor:
# Now you should be able to access the fields as properties of "row"
myVar1 = row.field1
myVar2 = row.field2
conn.close()
import mysql.connector as mysql
...
cursor = mysql.cnx.cursor()
cursor.execute('select max(id) max_id from ids')
(id) = [ id for id in cursor ]
언급URL : https://stackoverflow.com/questions/10195139/how-to-retrieve-sql-result-column-value-using-column-name-in-python
'programing' 카테고리의 다른 글
| Python을 사용하여 JSON 문자열을 dict로 변환 (0) | 2023.01.06 |
|---|---|
| JavaScript / jQuery에서 HTML 태그를 얻는 방법 (0) | 2023.01.06 |
| Composer에서 패키지를 전체적으로 제거하려면 어떻게 해야 합니까? (0) | 2023.01.06 |
| guava와 apache 등가 라이브러리의 큰 개선점은 무엇입니까? (0) | 2023.01.06 |
| JPA: 동일한 엔티티 유형의 일대다 관계를 갖는 방법 (0) | 2023.01.06 |