开发者

How can I check if OpenSQLConnection was successful (in Mathematica)?

开发者 https://www.devze.com 2022-12-24 05:36 出处:网络
How can I check if DatabaseLink`OpenSQLConnection was successful? My code is as follows conn = OpenSQLConnection[JDBC[\"hsqldb\", \"file\"], \"Name\"-> \"test\"];

How can I check if DatabaseLink`OpenSQLConnection was successful? My code is as follows

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

Can I use something like Head[开发者_运维技巧conn]?


The return value for successful connection will have head SQLConnection (in the DatabaseLink context)

More generally:

OpenSQLConnection returns $Failed when the connection failed for whatever reason:

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 

... and unevaluated when its arguments were not of the proper form:

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

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

Therefore, you can look for a return value of $Failed and optionally also use Check[...] to trap and handle messages that were generated. As you guessed, you can use Head[returnvalue] to make sure the head of the return value does not equal OpenSQLConnection.


This is not exactly an answer to your question, but this is what I do to connect reliably to my database:

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"]
];
0

精彩评论

暂无评论...
验证码 换一张
取 消