【发布时间】:2015-05-18 11:36:06
【问题描述】:
如果我使用自定义 main(void main() 而不是 shared static this()),一切正常。
使用默认 main 我收到“访问冲突”错误。看起来 MySQL 不允许从 localhost 连接到它,但在 my.ini 中我添加了字符串:
bind-address = 127.0.0.1
代码,如果有帮助:
import std.stdio;
import std.path;
import std.file;
import std.string;
import dini;
import vibe.d;
import colorize;
import ddbc.all;
shared static this()
{
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];
listenHTTP(settings, &hello);
auto parseconfig = new ParseConfig();
auto db = new DBConnect(parseconfig);
}
void hello(HTTPServerRequest req, HTTPServerResponse res)
{
res.writeBody("Hello, World!");
}
class ParseConfig
{
string dbname;
string dbuser;
string dbpass;
string dbhost;
string dbport;
this()
{
try
{
//getcwd do not return correct path if run from task shoulder
string confpath = buildPath((thisExePath[0..((thisExePath.lastIndexOf("\\"))+1)]), "config.ini");
//writefln(thisExePath[0..((thisExePath.lastIndexOf("\\"))+1)]); // get path without extention +1 is for getting last slash
//string confpath = buildPath(thisExePath, "config.ini");
if (!exists(confpath))
{
writeln("ERROR: config.ini do not exists");
}
auto config = Ini.Parse(confpath);
try
{
this.dbname = config.getKey("dbname");
this.dbuser = config.getKey("dbuser");
this.dbpass = config.getKey("dbpass");
this.dbhost = config.getKey("dbhost");
this.dbport = config.getKey("dbport");
}
catch (Exception msg)
{
cwritefln("ERROR: Can't parse config: %s".color(fg.red), msg.msg);
}
}
catch(Exception msg)
{
cwriteln(msg.msg.color(fg.red));
core.thread.Thread.sleep( dur!("msecs")(1000));
}
}
}
class DBConnect
{
Statement stmt;
ParseConfig parseconfig;
this(ParseConfig parseconfig)
{
try
{
this.parseconfig = parseconfig;
MySQLDriver driver = new MySQLDriver();
string url = MySQLDriver.generateUrl(parseconfig.dbhost, to!short(parseconfig.dbport), parseconfig.dbname);
string[string] params = MySQLDriver.setUserAndPassword(parseconfig.dbuser, parseconfig.dbpass);
DataSource ds = new ConnectionPoolDataSourceImpl(driver, url, params);
auto conn = ds.getConnection();
scope(exit) conn.close();
stmt = conn.createStatement();
writefln("\n[Database connection OK]");
}
catch (Exception ex)
{
writefln(ex.msg);
writeln("Could not connect to DB. Please check settings");
}
}
}
我也运行下一个命令:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
我也尝试了不同的bind-address,例如:0.0.0.0 和localhost,但没有结果。每次新绑定后,我都会重启 MySQL 服务。
我正在使用这个驱动程序http://code.dlang.org/packages/ddbc
怎么了?
【问题讨论】:
-
授予后,你有
flush privileges;吗? -
是的,我做到了
flush privileges; -
GRANT ... @'127.0.0.1'... -
你能把它运行到一个'runTask'中吗? (vibed.org/api/vibe.core.core/runTask) 目前您正尝试在事件循环开始之前 连接到数据库,这会在所有模块构造函数返回后发生。诸如listenHTTP(乍一看似乎阻塞)之类的东西只不过是在全局列表(github.com/rejectedsoftware/vibe.d/blob/…)上注册一个服务器上下文。
-
好的,我现在就试试。但是为什么你说我连接之前 我认为甚至循环都以
static this()开头。因为即使循环只能在所有函数构造函数返回后才能启动,很难理解它如何完成其他任务。还是我有什么不明白的?