9月 08

go语言连接mysql成功

  go语言取mysql数据。之前的测试并没有成功,也没有找到原因,但是今天编译了一下又成功了,具体修改了哪里我也忘了。赶紧做个记录。敏感信息已经隐藏

  获得go语言的mysql驱动
go get code.google.com/p/go-mysql-driver/mysql
也可以
驱动安装
go get github.com/go-sql-driver/mysql
go install github.com/go-sql-driver/mysql

2013-5-27修正:该mysql驱动被移到git以后使用“$ go get github.com/go-sql-driver/mysql”
项目里调用为“import _ “github.com/go-sql-driver/mysql””

源码如下:

package main

import ("database/sql"
         _ "code.google.com/p/go-mysql-driver/mysql"
        "fmt")

func main() {
    db, e := sql.Open("mysql", "simon:zhang@tcp(127.0.0.1:3306)/simonzhang?charset=utf8")
    if e != nil {
        print("ERROR")
        return
    }
    println("Conn DB OK")
    rows, e := db.Query("select user,passwd from user")
    if e != nil {
        fmt.Print("error:%v\n", e)
        return
    }
    if rows == nil {
        print("Rows is nil")   
        return
    }
    for rows.Next() {
        var u,p string
        err := rows.Scan(&u,&p)
        if err != nil {
            print("Row error!")
            return
        }
        fmt.Println(u," ",p)
    }
    println("WIN!")
}

运行结果

7月 08

python mongodb 变量做集合(collection)名

【2011-7-8 张子萌】
当前需求:1)将某个目录下的html文件插入到mongo数据库中。
2)cellection名为html页的上级目录名。
3)document为文件名、html内容

测试目录位置/home/test

#!/usr/bin/python
#-*- coding:utf-8 -*-
import re
import os
import pymongo

find_file=re.compile(r”.html$”)
find_path=r”/home/test”
find_walk=os.walk(find_path)
conn = pymongo.Connection(“localhost”,27017)
db = conn.mytest
for path,dirs,files in find_walk:
for file in files:
if find_file.search(file):
collection_name=path.split(“/”)[2]
get_html=open(path+”/”+file,’r’)
exec(‘db.’+collection_name+’.save({“file_name”:file,”context”:get_html.read()})’)
get_html.close()

遇到一个问题,好像collection如只是数字(int)插入有问题,所以如果用数字名做collection名可以在前面加个字母。

6月 27

python测试连接mongodb 简单读写

下载pymongo模块,测试机python为2.6.6
[2011-6-27 张子萌]
# wget http://pypi.python.org/packages/source/p/pymongo/pymongo-1.11.tar.gz
解压安装
# tar zxvf pymongo-1.11.tar.gz
# cd pymongo-1.11
# python setup.py install

安装比较简单,下面写一个脚本测试一下是否成功。返回的也是dict。

#!/usr/bin/python
#-*- coding:utf-8 -*-
import pymongo
conn = pymongo.Connection(“localhost”,27017)
db = conn.mytest
cursor = db.mytest.find()
for i in cursor:
print i

有结果就ok了。

a)测试1存取二进制

插入MP3试试看。首先上传一个test.mp3,然后把MP3转为二进制,最后入库。
#!/usr/bin/python
#-*- coding:utf-8 -*-
import pymongo
import bson
conn = pymongo.Connection(“localhost”,27017)
db = conn.mytest
get_mp3=open(‘test.mp3′,’rb’) #以二进制方法读取MP3
bin=bson.Binary(get_mp3.read()) #转换对象
db.mytest.save({“file_name”:”test_mp3″,”mp3″:bin}) #保存入库
get_mp3.close()

如库查询看到以下结果,MP3已经入库成功。
> db.mytest.find({},{file_name:1})
{ “_id” : ObjectId(“4e0a70d0b4a1024472000000”), “file_name” : “test_mp3” }

现在在把MP3读出来看看是否可以用。
#!/usr/bin/python
#-*- coding:utf-8 -*-
import pymongo
conn = pymongo.Connection(“localhost”,27017)
db = conn.mytest
cursor=db.mytest.find({“file_name” : “test_mp3”},{“mp3”:1})
file=open(‘123.mp3′,’wb’)
print >>file,cursor[0][“mp3”] #因为测试库中就有一首所以不用循环了
file.close

取出MP3试听是否成功。

b)测试2存取字符型。文本文件保存也可以用二进制,但是字符型更好,便于索引和
查找。
首先建立一个test.txt测试文本,内容如下:
first
second
three
four

用以下脚本入库
#!/usr/bin/python
#-*- coding:utf-8 -*-
import pymongo
conn = pymongo.Connection(“localhost”,27017)
db = conn.mytest
get_txt=open(‘test.txt’,’r’)
for line in get_txt: #也可以不用循环,将文件插入到一个值里
db.mytest.insert({“file_name”:”test_txt”,”content”:line})
get_txt.close()

入库完毕登录mongodb检查,结果如下:
> db.mytest.find({“file_name”:”test_txt”},{})
{ “_id” : ObjectId(“4e0a762bb4a1024508000000”), “content” : “firstn”, “file_name” : “test_txt” }
{ “_id” : ObjectId(“4e0a762bb4a1024508000001”), “content” : “secondn”, “file_name” : “test_txt” }
{ “_id” : ObjectId(“4e0a762bb4a1024508000002”), “content” : “threen”, “file_name” : “test_txt” }
{ “_id” : ObjectId(“4e0a762bb4a1024508000003”), “content” : “fourn”, “file_name” : “test_txt” }

现在在把文本读出来看看是否可以用。
#!/usr/bin/python
#-*- coding:utf-8 -*-
import pymongo
conn = pymongo.Connection(“localhost”,27017)
db = conn.mytest
cursor=db.mytest.find({“file_name” : “test_txt”},{“content”:1})
file=open(‘123.txt’,’a’)
for i in cursor:
print >>file,i[“content”]
file.close

查看文本已经输出,因为是追加,并且在库里保存了回车符“n”,所以输出的文件都会隔一行写一行。

http://api.mongodb.org/python/1.11/installation.html
http://pypi.python.org/pypi/pymongo/

5月 27

python连接oracle和mysql备忘

import cx_Oracle
    
def sql_comm(sql_run):
    db = cx_Oracle.connect(‘user’, ‘passwd’, ‘IP:port/sid’) 
    try:
        cursor=db.cursor()
    except cx_Oracle.ERROR,e:
        print “Error %d:%s”%(e.args[0],e.args[1])
    try:
           cursor.execute(sql_run)
    result_set=cursor.fetchall()
           cursor.close()
           db.commit()
           db.close()
    return result_set
    except e:
        print “Error %s”%(e.args[0])
        cursor.close()
        db.close()

python连接mysql

import MySQLdb

def sql_comm(sql_run):
        try:
                conn=MySQLdb.connect(host=host,user=username,passwd=pwd,db=database)
                cursor = conn.cursor()
        except MySQLdb.Error,e:
                print “Error %d:%s”%(e.args[0],e.args[1])
        try:
                cursor.execute(sql_run)
                result_set=cursor.fetchall()
                cursor.close()
                db.close()
                return result_set
        except MySQLdb.Error,e:
                print “Error %d:%s”%(e.args[0],e.args[1])
                cursor.close()
                db.close()

注意部分,在mysql修改数据时最好使用commit,如果只是select就不用了,不然得不到数据。
在oracle和mysql插入大量数据时,可以使用executemany,需要注意的是,oracle插入大量
数据时要将数据类型为元组,然后放到列表中。建议一次插入10000行。