『壹』 在python上怎麼使用sql
第一種辦法:
#導入SQLite驅動:
>>>importsqlite3
#連接到SQLite資料庫
#資料庫文件是test.db
#如果文件不存在,會自動在當前目錄創建:
>>>conn=sqlite3.connect('test.db')
#創建一個Cursor:
>>>cursor=conn.cursor()
#執行一條SQL語句,創建user表:
>>>cursor.execute('createtableuser(idvarchar(20)primarykey,namevarchar(20))')
<sqlite3.Cursorobjectat0x10f8aa260>
#繼續執行一條SQL語句,插入一條記錄:
>>>cursor.execute('insertintouser(id,name)values('1','Michael')')
<sqlite3.Cursorobjectat0x10f8aa260>
#通過rowcount獲得插入的行數:
>>>cursor.rowcount
1
#關閉Cursor:
>>>cursor.close()
#提交事務:
>>>conn.commit()
#關閉Connection:
>>>conn.close()
第二種辦法:
使用 SQLalchemy 等ORM 的庫。
『貳』 python怎麼打開資料庫文件
以打開mysql資料庫為例來說明:
#!/usr/bin/python
import MySQLdb
# 打開資料庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
#打開游標
cursor = db.cursor()
# 執行資料庫查詢
cursor.execute("SELECT VERSION()")
# 獲取結果集的第一行
data = cursor.fetchone()
print "Database version : %s " % data
# 關閉連接
db.close()
『叄』 python 怎樣使外部.sql腳本執行
直接調命令行工具導入啊。 否則就麻煩 了。需要解析主要的語句,比如create table和insert。最怕碰到復雜的引號,嵌套之類的。經常搞不定啊。
代碼挺復雜的。
『肆』 python操作oracle資料庫執行SQL語句並將結果導出到文本中,應該怎麼寫
你自己找找文檔把,這么基礎的東西還需要大神?大神就這么不值錢嗎?
『伍』 Python 能像處理資料庫 SQL 一樣處理 CSV 文件嗎
import csv
按行讀取
讀取第二列為20140907的,然後判斷第三列裡面是不是包含了SC,如果包含,計數器加1吧
『陸』 python 字元串處理 SQL查詢語句
>>> base = """("%(k)s" = '%(v)s')"""
>>> print ' and '.join([base % dict(k=k, v=v) for k,v in dict(name='tim', email='[email protected]').items()])
("email" = '[email protected]') and ("name" = 'tim')
>>>
另外: 強烈建議不採用拼接字元串的方式定義SQL,而是採用參數
『柒』 設計一個PYTHON 程序從文件中讀取 SQL 語句
你的文件內容是什麼?用的是什麼資料庫?數據表有多少欄位?返回的格式有什麼要求?你給的信息太少了!
『捌』 python 有沒有把sql結果,直接寫入文件的方法
python把資料庫查詢結果寫入文件的例子如下:
//以只讀方式打開nodeset.txt
file_nodeset=open("nodeset.txt","r")
file_relationship=open("follower_followee.txt","a")
t=file_nodeset.readline()
while(''!=t):
cur=conn.cursor()
cur.execute("select * from follower_followee where followee_id=%s",t)
rows=cur.fetchall()//從資料庫取出查詢結果的一行
for row in rows: //開始循環處理
if (row[0] in nodeSet):
print('haha')
file_relationship.write('%s %s\n' % (row[0],row[1])) //寫入文件
cur.close()
t=file_nodeset.readline()
file_nodeset.close()
file_relationship.close()
『玖』 python批量執行sql語句並列印結果到一個文件中
推薦使用「Office批量列印精靈」——Office文檔批量列印軟體,支持Word、Excel、Powerpoint、PDF等文檔的批量列印,且可使用虛擬列印機,將多個Office文檔轉換為PDF文件。
下載地址:http://www.yiyunsoftware.com
使用教程:http://jingyan..com/article/f00622280e4dd4fbd3f0c80e.html