项目中使用hibernate连接数据库,在执行一些特殊任务时,可能需要用到更加灵活的数据库连接。记录一下,方便以后使用
public static void main(String[] args){
//驱动名称
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名scutcs
String url = "jdbc:mysql://ip:port/database?useUnicode=true&characterEncoding=utf8";
// MySQL配置时的用户名
String user = "xxx";
// Java连接MySQL配置时的密码
String password = "xxx";
try {
// 加载驱动程序
Class.forName(driver);
// 连续数据库
Connection conn = DriverManager.getConnection(url, user, password);
if(!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
// statement用来执行SQL语句
Statement statement = conn.createStatement();
// 要执行的SQL语句
String sql = "SELECT * from xxx where ";
ResultSet rs = statement.executeQuery(sql);
HashMap<Integer,String> hm=new HashMap<Integer,String>();
int index=0;
while(rs.next()) {
String filename = rs.getString("FILENAME");
//System.out.println(filename);
hm.put(index,filename);
index++;
}
rs.close();
conn.close();
System.out.println("-----------------");
System.out.println("数据库中有" + hm.size()+"条数据" );
} catch(ClassNotFoundException e) {
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}