Connecting to SQL Server:
Connecting to SQL Server
suggest changeInstall the package:
$ pip install pymssql
import pymssql
SERVER = "servername"
USER = "username"
PASSWORD = "password"
DATABASE = "dbname"
connection = pymssql.connect(server=SERVER, user=USER,
password=PASSWORD, database=DATABASE)
cursor = connection.cursor() # to access field as dictionary use cursor(as_dict=True)
cursor.execute("SELECT TOP 1 * FROM TableName")
row = cursor.fetchone()
######## CREATE TABLE ########
cursor.execute("""
CREATE TABLE posts (
post_id INT PRIMARY KEY NOT NULL, message TEXT, publish_date DATETIME
)
""")
######## INSERT DATA IN TABLE ########
cursor.execute("""
INSERT INTO posts VALUES(1, "Hey There", "11.23.2016")
""")
# commit your work to database
connection.commit()
######## ITERATE THROUGH RESULTS ########
cursor.execute("SELECT TOP 10 * FROM posts ORDER BY publish_date DESC")
for row in cursor:
print(“Message: “ + row1 + “ | “ + “Date: “ + row[2])
if you pass as_dict=True to cursor
print(row[“message”])
connection.close()
You can do anything if your work is related with SQL expressions, just pass this expressions to the execute method(CRUD operations).
For with statement, calling stored procedure, error handling or more example check: pymssql.org
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
3List
22Reduce
27Classes
28Counting
31Set
42Tuple
45Enum
60setup.py
62Sockets
89urllib
92Idioms
104Stack
105Profiling
109Logging
111os module
118Mixins
120ArcPy
123Websockets
126Arrays
128Polymorphism
1322to3 tool
135Unicode
138Neo4j
140Curses
141Templates
145heapq
146tkinter
151Connecting to SQL Server
154Audio
155pyglet
156queue module
157ijson
160Flask
161Groupby
163pygame
165hashlib
166Gzip
167ctypes
170configparser
179sys module
185pyaudio
186shelve
191Contributors