MySql数据库连接

项目中使用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();   
		}   
	}   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值