I have this code and my question is, How declare variable "connection" to global variable? I need share connection in my project for other func
var connection = ???
do {
var configuration = PostgresClientKit.ConnectionConfiguration()
configuration.host = "127.0.0.1"
configuration.database = "example"
configuration.user = "bob"
configuration.credential = .scramSHA256(password: "welcome1")
let connection = try PostgresClientKit.Connection(configuration: configuration)
let text = "SELECT start();"
try connection.prepareStatement(text: text).execute()
} catch {
print(error)
}
I tried use struct, but still I have problem with declare conn - Value of type '[conn]' has no member 'prepareStatement' Any idea?
import UIKit
import PostgresClientKit
struct conn {
let conn : Connection
}
var myconnection = [conn]()
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
do {
var configuration = PostgresClientKit.ConnectionConfiguration()
configuration.host = "127.0.0.1"
configuration.database = "example"
configuration.user = "bob"
configuration.credential = .scramSHA256(password: "welcome1")
let aaa = try PostgresClientKit.Connection(configuration: configuration)
let bbb = conn ( conn: aaa)
myconnection.append(bbb)
let text = "SELECT start();"
try myconnection.prepareStatement(text: text).execute()
} catch {
print(error) // better error handling goes here
}
}
I'm not sure I understand what you're trying to do, but I think I see your problem. Your code is failing on this line:
try myconnection.prepareStatement(text: text).execute()
but myconnection
, as you've declared it above, is of type [conn]
:
var myconnection = [conn]()
If you want to call prepareStatement(text:)
on the first element of your array, you can do this:
try myconnection[0].conn.prepareStatement(text: text).execute()
You need the .conn
in the middle because the array is an array of conn
structs, which have conn
properties that are actually of type Connection
.
It's worth noting that, at least in this function, you could just call prepareStatement(text:)
on aaa
before you create bbb
out of it and store it in the array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.