本文整理汇总了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')