How do I connect to a MySQL Database in Python?

后端 未结 25 1587
眼角桃花
眼角桃花 2020-11-21 07:43

How do I connect to a MySQL database using a python program?

25条回答
  •  Happy的楠姐
    2020-11-21 08:22

    Also take a look at Storm. It is a simple SQL mapping tool which allows you to easily edit and create SQL entries without writing the queries.

    Here is a simple example:

    from storm.locals import *
    
    # User will be the mapped object; you have to create the table before mapping it
    class User(object):
            __storm_table__ = "user" # table name
            ID = Int(primary=True) #field ID
            name= 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
    

    To find and object use:

    michael = store.find(User, User.name == u"Michael").one()
    print str(user.ID) # 10
    

    Find with primary key:

    print store.get(User, 1).name #Mark
    

    For further information see the tutorial.

提交回复
热议问题