|
1/jdbc方式访问数据库
Java代码
- // 载入驱动
- Class.forName("com.mysql.jdbc.Driver");
// 建立连接 - Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/demo", "test", "test");
// 创建状态 - Statement stmt = con.createStatement();
// 执行SQL语句,返回结果集 - ResultSet rs = stmt.executeQuery("SELECT * FROM person");
// 对结果集进行处理
while (rs.next()) {
int id = rs.getInt("id"); - String name = rs.getString("name");
- Integer age = rs.getObject("age") == null ? null : rs.getInt("age");
- System.out.println(id + ": " + name + " " + age);
- }
// 释放资源 - stmt.close();
- con.close();
// 载入驱动 Class.forName("com.mysql.jdbc.Driver"); // 建立连接 Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/demo", "test", "test"); // 创建状态 Statement stmt = con.createStatement(); // 执行SQL语句,返回结果集 ResultSet rs = stmt.executeQuery("SELECT * FROM person"); // 对结果集进行处理 while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); Integer age = rs.getObject("age") == null ? null : rs.getInt("age"); System.out.println(id + ": " + name + " " + age); } // 释放资源 stmt.close(); con.close();
2/hibernate方式访问数据库
Java代码
- sessionFactory = new Configuration().configure().buildSessionFactory();
- Session session=sessionFactory.openSession();
- Transaction trans=session.beginTransaction();
- trans.begin();
//执行的是HQL语句 - Query query=session.createQuery("from Bike");
- Bike bike1=new Bike();
- bike1.setSerialNo(1);
- bike1.setFrame(2);
- bike1.setManufacturer("a");
- bike1.setModel("b");
- bike1.setStatus("7");
- bike1.setWeight(123.0);
- session.save(bike1);
- Iterator iterator=query.iterate();
while(iterator.hasNext()){ - Bike bike=(Bike)iterator.next();
- System.out.println(bike);
- }
- trans.commit();
- session.close();
|
|