示例#1
0
func (self *Connection) Close() {
	if self.handle == nil {
		return
	}
	C.mysql_close(self.handle)
	self.handle = nil
}
示例#2
0
//关闭一个连接
func (mysql *MySQL) Close() {
	C.mysql_close(mysql.my)
	mysql.my = nil
	if mysql.rs != nil {
		C.mysql_free_result(mysql.rs)
	}
	mysql.fi = nil
	return
}
示例#3
0
文件: mysql.go 项目: eden/mysqlgo
// The URL passed into this function should be of the form:
//
//   mysql://user:pass@host:port/database_name
//   mysql://user:pass@socket./database_name?socket=/tmp/mysql.sock
//
// Every option except for the database is optional, and missing items will be
// taken from the system-wide configuration.
//
// The scheme may be omitted:
//
//   //user:pass@host:port/database_name
//
func open(uri string) (conn db.Connection, err os.Error) {
	var host, uname, passwd, dbname, socket *C.char;
	var port C.uint;

	url, urlError := http.ParseURL(uri);
	if urlError != nil {
		err = MysqlError(fmt.Sprintf("Couldn't parse URL: %s", urlError));
		return;
	}

	if len(url.Scheme) > 0 && url.Scheme != "mysql" {
		err = MysqlError(fmt.Sprintf("Invalid scheme: %s", url.Scheme));
		return;
	}

	if len(url.Host) > 0 {
		if url.Host == "socket." {
			sock := strings.Split(url.RawQuery, "=", 2);
			if len(sock) != 2 || sock[0] != "socket" {
				err = MysqlError(
					fmt.Sprintf("Invalid socket specified: %s", url.RawQuery));
				return;
			}
			sock = strings.Split(sock[1], "&", 2);
			socket = C.CString(sock[0]);
		} else {
			hostport := strings.Split(url.Host, ":", 2);
			if len(hostport) == 2 && len(hostport[1]) > 0 {
				p, _ := strconv.Atoi(hostport[1]);
				port = C.uint(p);
			}
			if len(hostport[0]) > 0 {
				host = C.CString(hostport[0])
			}
		}
	}

	if len(url.Userinfo) > 0 {
		userpass := strings.Split(url.Userinfo, ":", 2);
		if len(userpass) == 2 && len(userpass[1]) > 0 {
			passwd = C.CString(userpass[1])
		}
		if len(userpass[0]) > 0 {
			uname = C.CString(userpass[0])
		}
	}

	if len(url.Path) > 0 {
		path := strings.Split(url.Path, "/", 2);
		if len(path) == 2 && len(path[0]) == 0 && len(path[1]) > 0 {
			dbname = C.CString(path[1])
		}
	}

	c := Connection{};
	c.lock = new(sync.Mutex);
	c.handle = C.mysql_init(nil);
	if c.handle == nil {
		err = MysqlError("Couldn't init handle (likely out of memory?)");
		goto cleanup;
	}

	rc := C.mysql_real_connect(
		c.handle,
		host,
		uname,
		passwd,
		dbname,
		port,
		socket,
		0);	// client flags

	// If an error was set, or if the handle returned is not the same as the
	// one we allocated, there was a problem.
	err = c.lastError();
	if err != nil || rc != c.handle {
		C.mysql_close(c.handle)
	} else {
		// Everything's ok, set the returned the connection
		conn = c
	}

cleanup:
	if host != nil {
		C.free(unsafe.Pointer(host))
	}
	if uname != nil {
		C.free(unsafe.Pointer(uname))
	}
	if passwd != nil {
		C.free(unsafe.Pointer(passwd))
	}
	if dbname != nil {
		C.free(unsafe.Pointer(dbname))
	}
	if socket != nil {
		C.free(unsafe.Pointer(socket))
	}

	return;
}