What's the simplest way to access mssql with python or ironpython?

前端 未结 8 2064
忘了有多久
忘了有多久 2020-12-04 16:56

I\'ve got mssql 2005 running on my personal computer with a database I\'d like to run some python scripts on. I\'m looking for a way to do some really simple access on the d

8条回答
  •  佛祖请我去吃肉
    2020-12-04 17:25

    Everyone else seems to have the cPython -> SQL Server side covered. If you want to use IronPython, you can use the standard ADO.NET API to talk to the database:

    import clr
    clr.AddReference('System.Data')
    from System.Data.SqlClient import SqlConnection, SqlParameter
    
    conn_string = 'data source=; initial catalog=; trusted_connection=True'
    connection = SqlConnection(conn_string)
    connection.Open()
    command = connection.CreateCommand()
    command.CommandText = 'select id, name from people where group_id = @group_id'
    command.Parameters.Add(SqlParameter('group_id', 23))
    
    reader = command.ExecuteReader()
    while reader.Read():
        print reader['id'], reader['name']
    
    connection.Close()
    

    If you've already got IronPython, you don't need to install anything else.

    Lots of docs available here and here.

提交回复
热议问题