在我当前的项目中,每次用户提出请求时,我都会打开一个新的数据库连接。例如:
func login(w http.ResponseWriter, r *http.Request) {
...
db, err := sqlx.Connect("postgres", "user=postgres password=*** dbname=postgres")
if err != nil {
ErrorWithJSON(w, err.Error(), http.StatusBadRequest)
return
}
db.SetMaxIdleConns(0)
db.SetConnMaxLifetime(time.Second * 30)
user, err := loginManager(db, m)
...
err = db.Close()
}
Run Code Online (Sandbox Code Playgroud)
我在搜索别人的代码时看到,大部分开发者都创建了一个数据库连接的全局变量,设置在main上,然后在整个项目中使用这个变量。
我想知道这些方法有什么区别吗?如果我使用全局变量,当 5 个不同的用户请求注册/登录等时,会不会有任何延迟。提出请求。像一个简单的负载均衡器,我不知道?
抱歉有多个问题。谢谢!
我开始从Head First学习PHP和MySql,现在我在第2章,我正在从书中做一些练习.
$connection = mysql_connect("127.0.0.1", "root", "", "aliendatabase")
or die ("Oops! Couldn't connect to server because ". mysql_error());
$sql="INSERT INTO aliens_abduction (first_name, last_name, when_it_happened, how_long, how_many, alien_description, what_they_did, fang_spotted, other, email)
VALUES ('$first_name', '$last_name', '$when_it_happened', '$how_long', 'how_many', '$alien_description', '$what_they_did', '$fang_spotted', '$other', '$email')";
mysqli_query($connection, $sql)
or die('Error querying database.' . mysql_error());
mysqli_close($connection);
Run Code Online (Sandbox Code Playgroud)
当我写这个部分时,我不断收到"查询数据库错误"错误.任何人都可以告诉我这段代码有什么问题吗?