0.Contents
1.Preface
2.Preparation
3.Simple test statement
4.Submit and rollback
5. How to write encapsulated into classes
1. Preface
After learning the basic syntax of SQL Server, let’s learn how to use sql in the program. After all, it cannot be used in the program. If used, the practicality is not that great.
2. The most basic SQL query statement
Python uses the pymssql module to operate the SQL Server database, so you need to install pymssql first.
Enter this directly in the command linepip install pymssql
Just install it
Then you need to configure your local SQL Server database and enter Microsoft SQL Server Management Studio to set it up . If you choose to use Windows authentication, you need to change it to SQL authentication. There are many tutorials on this online, just search and you will find them.
3. Simple test statement
Open IDLE and create a new python program:
import pymssql conn = pymssql.connect(host='127.0.0.1', user='sa', password='123', database='SQLTest', charset='utf8')#查看连接是否成功cursor = conn.cursor() sql = 'select * from student'cursor.execute(sql)#用一个rs变量获取数据rs = cursor.fetchall()print(rs)
4. Submit and rollback
In python, after completing the "add, delete, modify" operation, you need to execute commit() to actually submit the code for execution. If something unexpected happens, execute rollback() to roll back to the previous state, which is equivalent to all the previous operations being in vain. Done, this also protects the database.
So it is recommended to write a program like this:
try: conn = pymssql.connect(host='127.0.0.1', user='sa', password='123', database='SQLTest', charset='utf8') cursor = conn.cursor() sql = 'insert into student values('0001', '张三', 18, '男', '文学院')' cursor.execute(sql) conn.commit()except Exception as ex: conn.rollback() raise exfinally: conn.close()
You can try deleting conn.commit(), and then see if there are changes in the database.
5. How to encapsulate it into a class
''' TestDB类 功能:测试数据库的类写法 作者:PyLearn 最后修改日期: 2017/10/17''' import pymssql class TestDB(): def __init__(self): try: self.conn = pymssql.connect(host='127.0.0.1', user='sa', password='123', database='SQLTest', charset='utf8') self.cursor = self.conn.cursor() self.sql = "insert into student values('0001', '张三', 18, '男', '文学院')" self.cursor.execute(self.sql) self.conn.commit() except Exception as ex: self.conn.rollback() raise ex finally: self.conn.close()if __name__ == '__main__': test_DB = TestDB()
The above is the detailed content of How to operate SQL Server database in Python. For more information, please follow other related articles on the PHP Chinese website!

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use
