Python CREATE Database

Source: Internet
Author: User


Yesterday with Shell script to create a database, involving Java calls, compare toss, instead of using Python to create a database directly, it is more convenient, good, directly on the code, the relevant comments also added

# _*_encoding:utf-8_*_
Import MySQLdb

Db_host = ' '
Db_user = ' '
DB_PW = ' '
db_name = ' VDT '


def cre_db (host, user, PW, name):
Try
# Database connection
db = MySQLdb.connect (host, user, PW, charset= ' UTF8 ')
# Create cursors through connection and data communication
cursor = Db.cursor ()
# Execute SQL statement
Cursor.execute (' Show databases ')
rows = Cursor.fetchall ()
For row in rows:
TMP = "%2s"% row
# Determine if the database exists
If name = = tmp:
Cursor.execute (' drop database if exists ' + name)
Cursor.execute (' Create database if not exists ' + name)
# Commit to Database execution
Db.commit ()
Except Mysqldb.error, E:
Print "Mysql Error%d:%s"% (E.args[0], e.args[1])
Finally
# Close the database connection
Db.close ()


cre_db (Db_host, Db_user, DB_PW)

Python CREATE Database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.