python连接mysql语句

python连接mysql

  1. import mysql.connector

  2. cnx = mysql.connector.connect(user='scott', password='tiger',
  3.                               host='127.0.0.1',
  4.                               database='employees')
  5. cnx.close()

  1. from mysql.connector import (connection)

  2. cnx = connection.MySQLConnection(user='scott', password='tiger',
  3.                                  host='127.0.0.1',
  4.                                  database='employees')

  1. import mysql.connector
  2. from mysql.connector import errorcode

  3. try:
  4.   cnx = mysql.connector.connect(user='scott',
  5.                                 database='testt')
  6. except mysql.connector.Error as err:
  7.   if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
  8.     print("Something is wrong with your user name or password")
  9.   elif err.errno == errorcode.ER_BAD_DB_ERROR:
  10.     print("Database does not exist")
  11.   else:
  12.     print(err)
  13. else:
  14.   cnx.close()

  1. import mysql.connector

  2. config = {
  3.   'user': 'scott',
  4.   'password': 'tiger',
  5.   'host': '127.0.0.1',
  6.   'database': 'employees',
  7.   'raise_on_warnings': True,
  8. }

  9. cnx = mysql.connector.connect(**config)

  10. cnx.close()

用Python 插入数据

  1. from __future__ import print_function
  2. from datetime import date, datetime, timedelta
  3. import mysql.connector

  4. cnx = mysql.connector.connect(user='scott', database='employees')
  5. cursor = cnx.cursor()

  6. tomorrow = datetime.now().date() + timedelta(days=1)

  7. add_employee = ("INSERT INTO employees "
  8.                "(first_name, last_name, hire_date, gender, birth_date) "
  9.                "VALUES (%s, %s, %s, %s, %s)")
  10. add_salary = ("INSERT INTO salaries "
  11.               "(emp_no, salary, from_date, to_date) "
  12.               "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

  13. data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))

  14. # Insert new employee
  15. cursor.execute(add_employee, data_employee)
  16. emp_no = cursor.lastrowid

  17. # Insert salary information
  18. data_salary = {
  19.   'emp_no': emp_no,
  20.   'salary': 50000,
  21.   'from_date': tomorrow,
  22.   'to_date': date(9999, 1, 1),
  23. }
  24. cursor.execute(add_salary, data_salary)

  25. # Make sure data is committed to the database
  26. cnx.commit()

  27. cursor.close()
  28. cnx.close()

用python查询数据

  1. import datetime
  2. import mysql.connector

  3. cnx = mysql.connector.connect(user='scott', database='employees')
  4. cursor = cnx.cursor()

  5. query = ("SELECT first_name, last_name, hire_date FROM employees "
  6.          "WHERE hire_date BETWEEN %s AND %s")

  7. hire_start = datetime.date(1999, 1, 1)
  8. hire_end = datetime.date(1999, 12, 31)

  9. cursor.execute(query, (hire_start, hire_end))

  10. for (first_name, last_name, hire_date) in cursor:
  11.   print("{}, {} was hired on {:%d %b %Y}".format(
  12.     last_name, first_name, hire_date))

  13. cursor.close()
  14. cnx.close()


附录: 连接字符串的参数

Argument Name Default Description
user (username*)   The user name used to authenticate with the MySQL server.
password (passwd*)   The password to authenticate the user with the MySQL server.
database (db*)   The database name to use when connecting with the MySQL server.
host 127.0.0.1 The host name or IP address of the MySQL server.
port 3306 The TCP/IP port of the MySQL server. Must be an integer.
unix_socket   The location of the Unix socket file.
auth_plugin   Authentication plugin to use. Added in 1.2.1.
use_unicode True Whether to use Unicode.
charset utf8 Which MySQL character set to use.
collation utf8_general_ci Which MySQL collation to use.
autocommit False Whether to autocommit transactions.
time_zone   Set the time_zone session variable at connection time.
sql_mode   Set the sql_mode session variable at connection time.
get_warnings False Whether to fetch warnings.
raise_on_warnings False Whether to raise an exception on warnings.
connection_timeout(connect_timeout*)   Timeout for the TCP and Unix socket connections.
client_flags   MySQL client flags.
buffered False Whether cursor objects fetch the results immediately after executing queries.
raw False Whether MySQL results are returned as is, rather than converted to Python types.
ssl_ca   File containing the SSL certificate authority.
ssl_cert   File containing the SSL certificate file.
ssl_key   File containing the SSL key.
ssl_verify_cert False When set to True, checks the server certificate against the certificate file specified by the ssl_ca option. Any mismatch causes a ValueError exception.
force_ipv6 False When set to True, uses IPv6 when an address resolves to both IPv4 and IPv6. By default, IPv4 is used in such cases.
dsn   Not supported (raises NotSupportedError when used).
pool_name   Connection pool name. Added in 1.1.1.
pool_size 5 Connection pool size. Added in 1.1.1.
pool_reset_session True Whether to reset session variables when connection is returned to pool. Added in 1.1.5.
compress False Whether to use compressed client/server protocol. Added in 1.1.2.
converter_class   Converter class to use. Added in 1.1.2.
fabric   MySQL Fabric connection arguments. Added in 1.2.0.
failover   Server failover sequence. Added in 1.2.1.
option_files   Which option files to read. Added in 2.0.0.
option_groups ['client', 'connector_python'] Which groups to read from option files. Added in 2.0.0.
allow_local_infile True Whether to enable LOAD DATA LOCAL INFILE. Added in 2.0.0.
use_pure True Whether to use pure Python or C Extension. Added in 2.1.1.




常见错误:
1. 连接mysql错误: mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost' (111)
python脚本:
  1. __author__ = 'root'

  2. import mysql.connector
  3. import locale

  4. locale.setlocale(locale.LC_ALL,'C')

  5. logMysql = mysql.connector.connect(host='localhost',port='1333',user='root',password='Pingan@phzc12345678',database='log');
  6. logMysql.close();
执行后报错:
  1. /usr/bin/python /root/PycharmProjects/untitled/testMysql.py
  2. Traceback (most recent call last):
  3.   File "/root/PycharmProjects/untitled/testMysql.py", line 8, in <module>
  4.     logMysql = mysql.connector.connect(host='localhost',port='1333',user='root',password='Pingan@phzc12345678',database='log');
  5.   File "/usr/lib/python2.6/site-packages/mysql/connector/__init__.py", line 44, in Connect
  6.     return MySQLConnection(*args, **kwargs)
  7.   File "/usr/lib/python2.6/site-packages/mysql/connector/connection.py", line 108, in __init__
  8.     self.connect(**kwargs)
  9.   File "/usr/lib/python2.6/site-packages/mysql/connector/connection.py", line 356, in connect
  10.     self._open_connection()
  11.   File "/usr/lib/python2.6/site-packages/mysql/connector/connection.py", line 319, in _open_connection
  12.     self._socket.open_connection()
  13.   File "/usr/lib/python2.6/site-packages/mysql/connector/network.py", line 393, in open_connection
  14.     errno=2003, values=(self.server_host, msg))
  15. mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost
解决: 在 mysql . connector . connect 中增加参数:unix_socket='/tmp/mysql.sock',即 my.cnf 中 socket 配置对应的值;


2 插入数据
    执行插入操作后,没有任何报错提示,但是数据就是没有插入到相应的表中。
 解决:
    是由于少些了两行代码,没有提交和关闭游标
       logMysql.commit();
       cursor.close();
    
  1. addBackupLog=(
  2.         "INSERT INTO log_innobackupex(BACKUP_TYPE, DIR_NAME, BACKUP_STATUS, BACKUP_DIR, TAR_STATUS, TAR_DIR, SCP_STATUS, SCP_DIR) "
  3.         "VALUES(%s,%s,%s,%s,%s,%s,%s,%s)"
  4.     );

  5.     dataBackupLog=('FULL',max_dir_name, str(backIsSucc),directory+max_dir_name,str(tar_cmd),
  6.                    directory+'tar_full/'+max_dir_name+'.tar.gz',str(scp_status),scp_server)
  7.     """

  8.     addBackupLog=(
  9.         "INSERT INTO log_innobackupex(BACKUP_TYPE) "
  10.         "VALUES(%s)"
  11.     );

  12.     dataBackupLog=('FULL')
  13.     """

  14.     try:
  15.         logMysql = mysql.connector.connect(user='****',password='********',host='localhost',database='log',port='3306',unix_socket='/tmp/mysql.sock',charset='utf8');
  16.         cursor = logMysql.cursor();
  17.         cursor.execute(addBackupLog,dataBackupLog);

  18.         logMysql.commit();
  19.         cursor.close();
  20.     except errorcode:
  21.         print(errorcode);

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30150152/viewspace-1778520/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/30150152/viewspace-1778520/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值