我在内存数据库中构建了H2用于短期存储。我从一个简短的Java存根和测试连接到数据库,以确保我已成功连接。由于它很短,我已经完整地包含了代码。我已经使用了.isClosed和isValid(0)。关闭始终返回负数(意味着未关闭),isValid(0)始终以正数回答(意味着未关闭)。无论我使用有效凭证还是假冒
,它们都表现得那样public class H2SeeWhatICabBreak {
public static Connection getConnection() {
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(-1);
}
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", "<username>");
connectionProps.put("password", "<password>");
try {
conn = DriverManager.getConnection("jdbc:h2:~/tickets");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(-1);
}
return conn;
}
public static void main(String[] args) throws SQLException {
Connection dbCTX = getConnection();
if (dbCTX == null ) {
System.err.println("Got back a null, good bye!!");
System.exit(-1);
}
if (dbCTX.isClosed())
{
System.err.println("There's something rotten in River City");
} else {
System.err.println("Got connection");
}
System.err.println("Looks like we did it??");
}
}
有什么想法吗?
答案 0 :(得分:0)
您创建并设置baseQuery := `
SELECT *
FROM
tableName
WHERE
(name ILIKE $1)`
params := []interface{}{"%" + nameLike + "%"}
// you can add optional criteria using this way
if condition==true {
baseQuery += fmt.Sprintf(` AND student_no=$%d`, len(params)+1)
params = append(params, studentNo)
}
filterQuery := baseQuery + ` ORDER BY contract_no ASC`
if totalLimit != 0 {
filterQuery += fmt.Sprintf(` LIMIT $%d OFFSET $%d`, len(params)+1, len(params)+2)
params = append(params, totalLimit, totalSkip)
}
rows, err := db.Query(filterQuery, params...)
,但实际上 。您的代码等同于以下内容。请注意,H2的默认用户名和密码是空字符串。
connectionProps
或
conn = DriverManager.getConnection("jdbc:h2:~/tickets");
或
conn = DriverManager.getConnection("jdbc:h2:~/tickets", "", "");
或
conn = DriverManager.getConnection("jdbc:h2:~/tickets", null);
您要做的是:
conn = DriverManager.getConnection("jdbc:h2:~/tickets", new Properties());
或(更复杂):
conn = DriverManager.getConnection("jdbc:h2:~/tickets",
"<username>", "<password>");