1.jdbc连接数据库
package com.hu.demo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class DBHelper { public static final String url = "jdbc:mysql://127.0.0.1/student"; public static final String name = "com.mysql.jdbc.Driver"; public static final String user = "root"; public static final String password = "root"; public Connection conn = null; public PreparedStatement pst = null; public DBHelper(String sql) { try { Class.forName(name);//指定连接类型 conn = DriverManager.getConnection(url, user, password);//获取连接 pst = conn.prepareStatement(sql);//准备执行语句 } catch (Exception e) { e.printStackTrace(); } } public void close() { try { this.conn.close(); this.pst.close(); } catch (SQLException e) { e.printStackTrace(); } } }
package com.hu.demo; import java.sql.ResultSet; import java.sql.SQLException; public class Demo { static String sql = null; static DBHelper db1 = null; static ResultSet ret = null; public static void main(String[] args) { sql = "select *from stuinfo";//SQL语句 db1 = new DBHelper(sql);//创建DBHelper对象 try { ret = db1.pst.executeQuery();//执行语句,得到结果集 while (ret.next()) { String uid = ret.getString(1); String ufname = ret.getString(2); String ulname = ret.getString(3); String udate = ret.getString(4); System.out.println(uid + "\t" + ufname + "\t" + ulname + "\t" + udate ); }//显示数据 ret.close(); db1.close();//关闭连接 } catch (SQLException e) { e.printStackTrace(); } } }
2.Spring + JdbcTemplate + JdbcDaoSupport
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="test" class="jdbc.Test"> <property name="dataSource" ref="dataSource"></property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/testspring" /> <property name="username" value="root" /> <property name="password" value="" /> </bean> </beans>
spring
package jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void insert(User u) { String sql = "insert into _user " + "values(null, ?, ?)";//普通的sql语句 Connection conn = null; try { conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, u.getName()); ps.setString(2, u.getPassword()); ps.executeUpdate(); ps.close(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } } public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); Test t = (Test) ctx.getBean("test"); User u = new User(); u.setName("dd"); u.setPassword("dd"); t.insert(u); } }
JdbcTemplate
package jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; public class Test { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void insert(User u) { String sql = "insert into _user " + "values(null, ?, ?)";//普通的sql语句 JdbcTemplate template = new JdbcTemplate(dataSource); template.update(sql, new Object[]{u.getName(), u.getPassword()}); } public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); Test t = (Test) ctx.getBean("test"); User u = new User(); u.setName("dd"); u.setPassword("dd"); t.insert(u); } }
JdbcDaoSupport
package jdbc; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.support.JdbcDaoSupport; public class Test extends JdbcDaoSupport { //JdbcDaoSupport类已经有了public final void setDataSource(DataSource dataSource)了 //不用重写也不能重写 public void insert(User u) { String sql = "insert into _user " + "values(null, ?, ?)";//普通的sql语句 this.getJdbcTemplate().update(sql, new Object[]{u.getName(), u.getPassword()}); } public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); Test t = (Test) ctx.getBean("test"); User u = new User(); u.setName("dd"); u.setPassword("dd"); t.insert(u); } }
参考博文http://hzy3774.iteye.com/blog/1689525
hibernate
public List<UserPO> LoginUser(UserPO up)throws Exception{ Session session = HibernateSessionFactory.getSession(); String hql = "from UserPO where name = ? and pwd= ?"; Query query = session.createQuery(hql); query.setString(0, up.getName()); query.setString(1, up.getPwd()); List<UserPO> list = query.list(); session.close(); return list; } // 建工厂类HibernateUtil package com.historycreator.hibernate; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } //建类EventManager package com.historycreator.hibernate; import java.util.Date; import org.hibernate.classic.Session; public class EventManager { public static void main(String[] args) { EventManager mgr = new EventManager(); mgr.createAndStoreEvent("My Event", new Date()); HibernateUtil.getSessionFactory().close(); } private void createAndStoreEvent(String title, Date theDate) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate); session.save(theEvent); session.getTransaction().commit(); } }