python SQL Serverに接続してデータを読み出し、単語処理をしてSQL Serverに書き込む
9191 ワード
この間、仮想マシンでMySQL全体が少しクラッシュしました.3306ポートとマッピングポートがインバウンドルールでオープンしているのに、外部ネットワークにアクセスできません.需要がMySQLからSQL Serverに変わったので、またSQL Severを始めました.しかしSQL Serverもそんなに操作が上手ではありません.初心者の初めての操作はきっと苦労しなければなりません.
当機は操作して半分の午後やっと任務を完成しました:SQL Serverの中のデータを読み取って、ぐずぐずして分詞した後に新しい表の中で保存します
1.まずpymssqlのインストールです.このライブラリはpythonコードをSQL Serverに接続できます.
2.次に指定したデータベースへの接続
3.接続後、指定したデータベースの値を読み出す
4.分詞処理を行い、SQL serverデータベースに書き込む.書き込み操作は最大のピットです
単一引用符の問題だけで私を困惑させた午後、ルームメイトの指導がなければ、私は任務を完成できないに違いない.事実はプログラミングが困難な過程であることを証明し、友达との助けを蓄積する必要がある.
当機は操作して半分の午後やっと任務を完成しました:SQL Serverの中のデータを読み取って、ぐずぐずして分詞した後に新しい表の中で保存します
1.まずpymssqlのインストールです.このライブラリはpythonコードをSQL Serverに接続できます.
pip install pymssql
2.次に指定したデータベースへの接続
server = 'xxx.xxx.xxx.xxx:xxxx'
user = 'xsf'
password = 'xxxxxx'
# ip ,ssms ,
conn = pymssql.connect(server, user, password, 'XSF')
cursor = conn.cursor()
3.接続後、指定したデータベースの値を読み出す
cursor.execute("select * from book;")
id_list = []
cut_list = []# id booktitle,
while 1:
res = cursor.fetchone()
if res is None:
break
id = res[0]
book_name = res[2]
words = psg.cut(book_name)
word_list = []
for word in words:
if word.flag != 'm' and word.flag != 'x' and word.flag != 'c' and word.flag != 'e' and len(
word.word) > 1 and word.flag != 'o':
word_list.append(word.word)
# , ,
id_list.append(id)
cut_list.append(word_list)
print(id)
print('ok')
#68 (68 ), (45 ),print ( , , SQL server, )
4.分詞処理を行い、SQL serverデータベースに書き込む.書き込み操作は最大のピットです
n = 0
for i in range(len(cut_list)):
id = id_list[i]
cut = cut_list[i]
try:
cursor.execute(
"INSERT INTO XSF.dbo.bookTitleKeyword(bookId, titleKeyword) VALUES ('%d', '%s')" % (id, cut))
#sql
#"INSERT INTO XSF.dbo.bookTitleKeyword(bookId, titleKeyword) VALUES ('%d,%s')" % (id, cut))
conn.commit()
print(' '+str(id)+' ')
except :
print(' , '+str(id))
n = n+1
pass
print(' , '+str(n))
cursor.close()
conn.commit()
conn.close()
単一引用符の問題だけで私を困惑させた午後、ルームメイトの指導がなければ、私は任務を完成できないに違いない.事実はプログラミングが困難な過程であることを証明し、友达との助けを蓄積する必要がある.