Home > Backend Development > Python Tutorial > Detailed example of teaching you how to connect to SQLServer2000 using Python

Detailed example of teaching you how to connect to SQLServer2000 using Python

Y2J
Release: 2017-05-03 16:24:37
Original
2120 people have browsed it

This article mainly introduces the method of Python connecting to SQLServer2000, and analyzes the common problems and related precautions encountered in Python's implementation of database connection in the form of examples. Friends in need can refer to this article

The example describes how Python connects to SQLServer2000. Share it with everyone for your reference, the details are as follows:

pymssql.sourceforge.net/ Introducing a good address for PYTHON to connect to MSSQL!

A good way for Python is to find many ready-made modules on the Internet and then download them directly and use them. One of the reasons for rapid development is this. Now we are mainly going to study the operating functions of the pymssql module!

You can directly query the help document after installation to view some function help documents of this module.

1. A method to solve the problem of garbled characters:

s.decode('gbk', 'ignore')
Copy after login

For example, if you want to convert a String object s from gbk internal code to UTF-8, you can do the following Operation

s.decode('gbk').encode('utf-8')
Copy after login

However, in actual development, I found that this method often produces exceptions:

UnicodeDecodeError: 'gbk' codec can't decode bytes in position 30664- 30665: illegal multibyte sequence

This is because an illegal character is encountered - especially in some programs written in C/C++, full-width spaces are often implemented in many different ways, such as / xa3/xa0, or /xa4/x57, these characters appear to be full-width spaces, but they are not "legal" full-width spaces (the real full-width spaces are /xa1/xa1), so they appear during the transcoding process Exception.

Fortunately, tiny found a perfect solution (I was criticized for not reading the documentation carefully, sweat...)

s.decode('gbk', 'ignore').encode('utf-8')
Copy after login

Because the function prototype of decode is decode([encoding] , [errors='strict']), you can use the second parameter to control the error handling strategy. The default parameter is strict, which means an exception will be thrown when an illegal character is encountered;

If set to ignore, illegal characters will be ignored;
If set to replace, illegal characters will be replaced with ?;
If set to xmlcharrefreplace, XML character references will be used.

This method is really helpful. For the problem of storing full-width and half-width illegal characters in the database, you can solve it like this!

The character encoding problem is always a headache, haha!

2.www.python.org/dev/peps/pep-0249/

The above provides common operating functions of Python-DBAPI.

Summarize the relevant API operation methods:

3. Summarize the general program process of connecting Python to the database as follows:

Step 1: Import related Module

where MYSQL:

import MySQLdb
Copy after login

where MSSQL:

import pymssql
Copy after login

Step 2: Open the connection

where MYSQL:

conn = MySQLdb.connect(self.dbhost,self.dbuser,self.dbpasswd,self.database)
Copy after login

where MSSQL:

conn = pymssql.connect(host=self.dbhost,user=self.dbuser,password=self.dbpasswd,database=self.database)
Copy after login

[This method is defined through its own function prototype]

Step 3: After the connection is completed, start creating a cursor. Use this object to send a request operation to the database.

Code:

curs = conn.cursor()
Copy after login

Equivalent to the Statement object in JAVA. Submit SQL commands through statements

The fourth step: Start sending SQL commands to the database server. You can do it like this

curs.execute(SQL)
Copy after login

For example:

curs.execute("select * from test")
Copy after login

The SQL command can be any SQL statement, which can be an INSERT operation, a DELETE operation, or a SELECT operation.

Please note that commit() is required after execution.

For example:

cursor.execute("insert into test(id) values(1)")
Copy after login

If the SELECT operation is executed, the fifth step is required:

The fifth step:

curs.execute("select * from test")
rows = curs.fetchall()
Copy after login

Among them fetchall() is just a method of our cursor object.

Now you can extract the relevant information

for i in range(len(rows)):
 print "Row",i,"name",rows[i][0],"value",rows[i][1]
Copy after login

Look at the code I wrote:

def test(self):
    conn = self.connect()
    sql="select * from bbs where id<20"
    curs = conn.cursor()  #得到一个游标对象
    curs.execute(sql)    #执行一个SQL语句
    rows=curs.fetchall()  #得到全部的查询结果集
    for i in range(len(rows)): #
      print "Row",i,"name",rows[i][3],"value",rows[i][4]
    conn.close()
Copy after login

I understand: through this method, the one-line record obtained is actually a Tuple data structure.

To get one of them, you can query it using a method similar to a two-dimensional array.

rows[1][0]: Indicates the value of the first position in the first record.

Then let’s take a look at extracting it from the database and then encoding and decoding it

for i in range(len(rows)):
      print rows[i][4].decode(&#39;gb2312&#39;, &#39;ignore&#39;).encode(&#39;gb2312&#39;)
Copy after login

The above is the detailed content of Detailed example of teaching you how to connect to SQLServer2000 using Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template