本文整理匯總了Python中pymysql.connect方法的典型用法代碼示例。如果您正苦於以下問題:Python pymysql.connect方法的具體用法?Python pymysql.connect怎麽用?Python pymysql.connect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pymysql
的用法示例。
在下文中一共展示了pymysql.connect方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: cursor
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def cursor(cursor_type=None):
global _connects, _curcon, _config
if cursor_type:
return _connects[_curcon]['connect'].cursor(cursor_type)
else:
return _connects[_curcon]['connect'].cursor(_config['cursor_type'])
# 以下查詢接口 使用者必須調用
# cur.close()
## 執行sql語句
示例2: realTestDialogAuthThreeAttempts
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def realTestDialogAuthThreeAttempts(self):
TestAuthentication.Dialog.m = {b'Password, please:': b'stillnotverysecret'}
TestAuthentication.Dialog.fail=True # fail just once. We've got three attempts after all
with TempUser(self.connections[0].cursor(), 'pymysql_3a@localhost',
self.databases[0]['db'], 'three_attempts', 'stillnotverysecret') as u:
pymysql.connect(user='pymysql_3a', auth_plugin_map={b'dialog': TestAuthentication.Dialog}, **self.db)
pymysql.connect(user='pymysql_3a', auth_plugin_map={b'dialog': TestAuthentication.DialogHandler}, **self.db)
with self.assertRaises(pymysql.err.OperationalError):
pymysql.connect(user='pymysql_3a', auth_plugin_map={b'dialog': object}, **self.db)
with self.assertRaises(pymysql.err.OperationalError):
pymysql.connect(user='pymysql_3a', auth_plugin_map={b'dialog': TestAuthentication.DefectiveHandler}, **self.db)
with self.assertRaises(pymysql.err.OperationalError):
pymysql.connect(user='pymysql_3a', auth_plugin_map={b'notdialogplugin': TestAuthentication.Dialog}, **self.db)
TestAuthentication.Dialog.m = {b'Password, please:': b'I do not know'}
with self.assertRaises(pymysql.err.OperationalError):
pymysql.connect(user='pymysql_3a', auth_plugin_map={b'dialog': TestAuthentication.Dialog}, **self.db)
TestAuthentication.Dialog.m = {b'Password, please:': None}
with self.assertRaises(pymysql.err.OperationalError):
pymysql.connect(user='pymysql_3a', auth_plugin_map={b'dialog': TestAuthentication.Dialog}, **self.db)
示例3: test_defer_connect
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def test_defer_connect(self):
import socket
for db in self.databases:
d = db.copy()
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(d['unix_socket'])
except KeyError:
sock = socket.create_connection(
(d.get('host', 'localhost'), d.get('port', 3306)))
for k in ['unix_socket', 'host', 'port']:
try:
del d[k]
except KeyError:
pass
c = pymysql.connect(defer_connect=True, **d)
self.assertFalse(c.open)
c.connect(sock)
c.close()
sock.close()
示例4: test_issue_17
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def test_issue_17(self):
"""could not connect mysql use passwod"""
conn = self.connections[0]
host = self.databases[0]["host"]
db = self.databases[0]["db"]
c = conn.cursor()
# grant access to a table to a user with a password
try:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
c.execute("drop table if exists issue17")
c.execute("create table issue17 (x varchar(32) primary key)")
c.execute("insert into issue17 (x) values ('hello, world!')")
c.execute("grant all privileges on %s.issue17 to 'issue17user'@'%%' identified by '1234'" % db)
conn.commit()
conn2 = pymysql.connect(host=host, user="issue17user", passwd="1234", db=db)
c2 = conn2.cursor()
c2.execute("select x from issue17")
self.assertEqual("hello, world!", c2.fetchone()[0])
finally:
c.execute("drop table issue17")
示例5: test_issue_114
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def test_issue_114(self):
""" autocommit is not set after reconnecting with ping() """
conn = pymysql.connect(charset="utf8", **self.databases[0])
conn.autocommit(False)
c = conn.cursor()
c.execute("""select @@autocommit;""")
self.assertFalse(c.fetchone()[0])
conn.close()
conn.ping()
c.execute("""select @@autocommit;""")
self.assertFalse(c.fetchone()[0])
conn.close()
# Ensure autocommit() is still working
conn = pymysql.connect(charset="utf8", **self.databases[0])
c = conn.cursor()
c.execute("""select @@autocommit;""")
self.assertFalse(c.fetchone()[0])
conn.close()
conn.ping()
conn.autocommit(True)
c.execute("""select @@autocommit;""")
self.assertTrue(c.fetchone()[0])
conn.close()
示例6: setup_method
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def setup_method(self, load_iris_data):
super(_EngineToConnMixin, self).load_test_data_and_sql()
engine = self.conn
conn = engine.connect()
self.__tx = conn.begin()
self.pandasSQL = sql.SQLDatabase(conn)
self.__engine = engine
self.conn = conn
yield
self.__tx.rollback()
self.conn.close()
self.conn = self.__engine
self.pandasSQL = sql.SQLDatabase(self.__engine)
# XXX:
# super(_EngineToConnMixin, self).teardown_method(method)
示例7: test_datetime_time
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def test_datetime_time(self):
# test support for datetime.time
df = DataFrame([time(9, 0, 0), time(9, 1, 30)], columns=["a"])
df.to_sql('test_time', self.conn, index=False)
res = read_sql_table('test_time', self.conn)
tm.assert_frame_equal(res, df)
# GH8341
# first, use the fallback to have the sqlite adapter put in place
sqlite_conn = TestSQLiteFallback.connect()
sql.to_sql(df, "test_time2", sqlite_conn, index=False)
res = sql.read_sql_query("SELECT * FROM test_time2", sqlite_conn)
ref = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
tm.assert_frame_equal(ref, res) # check if adapter is in place
# then test if sqlalchemy is unaffected by the sqlite adapter
sql.to_sql(df, "test_time3", self.conn, index=False)
if self.flavor == 'sqlite':
res = sql.read_sql_query("SELECT * FROM test_time3", self.conn)
ref = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
tm.assert_frame_equal(ref, res)
res = sql.read_sql_table("test_time3", self.conn)
tm.assert_frame_equal(df, res)
示例8: create_tables
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def create_tables(self, request):
self.conn = pymysql.connect(host="127.0.0.1",
user="piiuser",
password="p11secret",
database="piidb"
)
with self.conn.cursor() as cursor:
self.execute_script(cursor, char_data_types)
cursor.execute("commit")
cursor.close()
def drop_tables():
with self.conn.cursor() as drop_cursor:
self.execute_script(drop_cursor, self.char_db_drop)
logging.info("Executed drop script")
drop_cursor.close()
self.conn.close()
request.addfinalizer(drop_tables)
示例9: connect
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def connect(cls, host_endpoint, user, password, db):
return pymysql.connect(host=host_endpoint, user=user, password=password, db=db)
示例10: connect
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def connect(dbconf=None, reset=None, name='default', timeout=3500):
global _connects, _curcon, _config
con = None
# 新連接
if dbconf:
for (k,v) in _dbConfig.items():
if not k in dbconf:
dbconf[k] = v
con = pymysql.connect(**dbconf)
# 讀取緩存的連接
if not dbconf and name:
conn = _connects[name]
tiv = conn['timevalid']
ti = int(time.time())
if(ti>=tiv): # 重新激活連接
dbconf = conn['config']
conn['connect'].close()
conn['connect'] = pymysql.connect(**dbconf)
conn['timevalid'] = ti+timeout
con = conn['connect']
# 緩存新的連接
if dbconf and name:
ti = int(time.time())
_connects[name] = {
'name': name,
'connect': con,
'config': dbconf,
'timevalid': ti+timeout
}
# 設置默認連接
if reset or not _curcon:
_curcon = name
# 返回連接
return con
## 斷開連接
示例11: disconnect
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def disconnect(name='default'):
global _connects
if name in _connects:
_connects[name]['connect'].close()
del _connects[name]
## 獲得數據庫操作遊標
示例12: query
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def query(sql, cursor_type=None):
con = connect()
con.ping()
cur = cursor(cursor_type)
cur.execute(sql)
con.commit() #提交事務
cur.close()
return cur
## 查詢
# @param cursor=None 返回查詢的list數組
# cursor=True 直接返回cursor
示例13: main
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def main():
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='mysql')
cur = conn.cursor(pymysql.cursors.DictCursor)
#cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
print(cur.description)
print(cur.rowcount)
print(repr(cur))
for row in cur:
print(row)
cur.close()
conn.close()
示例14: __init__
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def __init__(self, host, port, user, password, db):
self.db = pymysql.connect(host=host, port=port, user=user, password=password, db=db,
charset='utf8', autocommit=True)
示例15: __init__
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import connect [as 別名]
def __init__(self, host, port, user, password, db):
self._commit_lock = Lock()
self.db = pymysql.connect(host=host, port=port, user=user, password=password, db=db, charset='utf8')