zoukankan      html  css  js  c++  java
  • Python连接SQLServer2000

    http://www.pymssql.org/en/stable/pymssql_examples.html

    实例

    import pymssql
    
    # 获取连接
    conn = pymssql.connect('127.0.0.1', 'sa', 'ddh123', "aaa")
    
    # 获取游标
    cursor = conn.cursor()
    
    # 执行sql
    sql = '''
        insert into t_user 
          (username,password,age,height)
        values 
          ('alice2', '1213', 19, 172)  
    '''
    num = cursor.execute(sql)  # 为占位符%s赋值
    
    # 提交事务
    conn.commit()
    
    # 关闭资源
    cursor.close()
    conn.close()
    from os import getenv
    import pymssql
    
    server = getenv("PYMSSQL_TEST_SERVER")
    user = getenv("PYMSSQL_TEST_USERNAME")
    password = getenv("PYMSSQL_TEST_PASSWORD")
    
    conn = pymssql.connect(server, user, password, "tempdb")
    cursor = conn.cursor()
    cursor.execute("""
    IF OBJECT_ID('persons', 'U') IS NOT NULL
        DROP TABLE persons
    CREATE TABLE persons (
        id INT NOT NULL,
        name VARCHAR(100),
        salesrep VARCHAR(100),
        PRIMARY KEY(id)
    )
    """)
    cursor.executemany(
        "INSERT INTO persons VALUES (%d, %s, %s)",
        [(1, 'John Smith', 'John Doe'),
         (2, 'Jane Doe', 'Joe Dog'),
         (3, 'Mike T.', 'Sarah H.')])
    # you must call commit() to persist your data if you don't set autocommit to True
    conn.commit()
    
    cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
    row = cursor.fetchone()
    while row:
        print("ID=%d, Name=%s" % (row[0], row[1]))
        row = cursor.fetchone()
    
    conn.close()

    使用迭代器

    conn = pymssql.connect(server, user, password, "tempdb")
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
    
    for row in cursor:
        print('row = %r' % (row,))
    
    conn.close()
  • 相关阅读:
    Uva11584 Partitioning by Palindromes
    GYM100741 A Queries
    Uva11400 Lighting System Design
    UVA12563 Jin Ge Jin Qu hao
    Uva116 Unidirectional TSP
    HDU2089 不要62
    BZOJ3670: [Noi2014]动物园
    Uva11384 Help is needed for Dexter
    Uva1347 Tour
    BZOJ1924: [Sdoi2010]所驼门王的宝藏
  • 原文地址:https://www.cnblogs.com/hzjdpawn/p/11618341.html
Copyright © 2011-2022 走看看