如何检查OpenSQLConnection是否成功(在Mathematica中)?

时间:2010-03-24 21:15:16

标签: wolfram-mathematica

如何检查DatabaseLink`OpenSQLConnection是否成功?我的代码如下

conn = OpenSQLConnection[JDBC["hsqldb", "file"], "Name"-> "test"];

我可以使用像Head [conn]这样的东西吗?

2 个答案:

答案 0 :(得分:2)

这不是您问题的答案,但这是我可靠地连接到我的数据库的方法:

Needs["DatabaseLink`"];

CloseSQLConnection[conn];

TimeConstrained[
    conn=OpenSQLConnection[ JDBC["mysql","localhost:3306/mydb"],
                            "Username"->"myuser",
                            "Password"->"mypw"],
    5,
    CloseSQLConnection[conn];
    conn=OpenSQLConnection[ JDBC["mysql","localhost:3306/mydb"],
                            "Username"->"myuser",
                            "Password"->"mypw"]
];

答案 1 :(得分:2)

成功连接的返回值将为SQLConnection(在DatabaseLink上下文中)

更一般地说:

当连接因任何原因失败时,

OpenSQLConnection会返回$Failed

In[25]:= OpenSQLConnection[JDBC["mysql", "localhost:3306/foo"], 
   "Username" -> "foo", "Password" -> "bar"]

During evaluation of In[25]:= JDBC::error: Access denied for user 'foo'@'localhost' (using password: YES) >>

Out[25]= $Failed 

......当其论点不合适时,未评估:

In[28]:= OpenSQLConnection[Sin[x]]

Out[28]= OpenSQLConnection[Sin[x]]

因此,您可以查找返回值$Failed,也可以选择使用Check[...]来捕获和处理生成的消息。正如您猜测的那样,您可以使用Head[returnvalue]来确保返回值的头部不等于OpenSQLConnection