#!/usr/bin/pythonimport MySQLdb
# Connectdb = MySQLdb.connect(host="localhost",user="appuser",passwd="",db="onco")
cursor = db.cursor()
# Execute SQL select statementcursor.execute("SELECT * FROM location")
# Commit your changes if writing# In this case, we are only reading data# db.commit()
# Get the number of rows in the resultsetnumrows = cursor.rowcount
# Get and display one row at a timefor x in range(0, numrows):row = cursor.fetchone()print row[0], "-->", row[1]
# Close the connectiondb.close()
#!/usr/bin/pythonimport MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhostuser="john", # your usernamepasswd="megajonhy", # your passworddb="jonhydb") # name of the data base
# you must create a Cursor object. It will let# you execute all the queries you needcur = db.cursor()
# Use all the SQL you likecur.execute("SELECT * FROM YOUR_TABLE_NAME")
# print all the first cell of all the rowsfor row in cur.fetchall():print row[0]
db.close()
import peeweefrom peewee import *
db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')
class Book(peewee.Model):author = peewee.CharField()title = peewee.TextField()
class Meta:database = db
Book.create_table()book = Book(author="me", title='Peewee is cool')book.save()for book in Book.filter(author="me"):print book.title
from storm.locals import *
# User will be the mapped object; you have to create the table before mapping itclass User(object):__storm_table__ = "user" # table nameID = Int(primary=True) #field IDname= Unicode() # field name
database = create_database("mysql://root:password@localhost:3306/databaseName")store = Store(database)
user = User()user.name = u"Mark"
print str(user.ID) # None
store.add(user)store.flush() # ID is AUTO_INCREMENT
print str(user.ID) # 1 (ID)
store.commit() # commit all changes to the database
要查找和使用对象:
michael = store.find(User, User.name == u"Michael").one()print str(user.ID) # 10
import pymysql.cursorsimport pymysql
# Connect to the databaseconnection = pymysql.connect(host='localhost',user='user',password='passwd',db='db',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
try:with connection.cursor() as cursor:# Create a new recordsql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save# your changes.connection.commit()
with connection.cursor() as cursor:# Read a single recordsql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"cursor.execute(sql, ('webmaster@python.org',))result = cursor.fetchone()print(result)finally:connection.close()
快速透明地替换现有代码中的MySQLdb
如果您有使用MySQLdb的现有代码,您可以使用以下简单过程轻松地将其替换为pymysql:
# import MySQLdb << Remove this line and replace with:import pymysqlpymysql.install_as_MySQLdb()
import pymysql.cursorsconnection = pymysql.connect(host='localhost',user='mahdi',password='mahdi',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)cursor = connection.cursor()cursor.execute("CREATE DATABASE IF NOT EXISTS "+database)connection.select_db(database)sql_create = "CREATE TABLE IF NOT EXISTS "+tablename+(timestamp DATETIME NOT NULL PRIMARY KEY)"cursor.execute(sql_create)connection.commit()cursor.close()
#!/usr/bin/pythonimport MySQLdb
try:db = MySQLdb.connect(host="localhost", # db server, can be a remote onedb="mydb" # databaseuser="mydb", # usernamepasswd="mydb123", # password for this username)
# Create a Cursor objectcur = db.cursor()
# Create a query string. It can contain variablesquery_string = "SELECT * FROM MY_TABLE"
# Execute the querycur.execute(query_string)
# Get all the rows present the databasefor each_row in cur.fetchall():print each_row
# Close the connectiondb.close()except Exception, e:print 'Error ', e
import mysql.connectorimport _mysqldb=_mysql.connect("127.0.0.1","root","umer","sys")#db=_mysql.connect(host,user,password,db)# Example of how to insert new values:db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")db.store_result()db.query("SELECT * FROM new1.table1 ;")#new1 is scheme table1 is table mysqlres= db.store_result()for i in range(res.num_rows()):print(result.fetch_row())
from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker, scoped_session
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")session_obj = sessionmaker(bind=engine)session = scoped_session(session_obj)
# insert into databasesession.execute("insert into person values(2, 'random_name')")session.flush()session.commit()
ORM方式
from sqlalchemy import Column, Integer, Stringfrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker, scoped_session
Base = declarative_base()engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")session_obj = sessionmaker(bind=engine)session = scoped_session(session_obj)
# Bind the engine to the metadata of the Base class so that the# declaratives can be accessed through a DBSession instanceBase.metadata.bind = engine
class Person(Base):__tablename__ = 'person'# Here we define columns for the table person# Notice that each column is also a normal Python instance attribute.id = Column(Integer, primary_key=True)name = Column(String(250), nullable=False)
# insert into databaseperson_obj = Person(id=12, name="name")session.add(person_obj)session.flush()session.commit()
import pymysql
# Connect to the databaseconn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='fax')
# Create a Cursor objectcur = conn.cursor()
# Execute the querycur.execute("SELECT * FROM fax.student")
# Read and print recordsfor row in cur.fetchall():print(row)
import mysql.connector
Hostname = "localhost"Username = "root"Password ="admin" #enter your MySQL password
#set connectionset_db_conn = mysql.connector.connect(host= Hostname, user=Username, password=Password)
if set_db_conn:print("The Connection between has been set and the Connection ID is:")#show connection idprint(set_db_conn.connection_id)
使用MySQL连接Django
在Django中,要将您的模型或项目连接到MySQL数据库,您需要安装mysqlClient库。
pip install mysqlclient
要配置您的Django设置,以便您的项目可以连接到MySQL数据库,您可以使用以下设置。
DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql','NAME': 'database_name','USER': 'username','PASSWORD': 'databasepassword@123','HOST': 'localhost', # Or an IP Address that your DB is hosted on'PORT': '3306',}