1、原始
Connection conn = null;String url = "jdbc:mysql://localhost:3306/emps?user=root&password=&useUnicode=true&characterEncoding=utf-8";try { //加载驱动 Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url); //conn=DriverManager.getConnection() String sql = "select * from tm_project where proj_id=1"; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery("select * from tm_project where proj_id=2"); if (rs.next()) { System.out.println(rs.getString("proj_name")); }} catch (Exception e) { e.printStackTrace();}
notice:1、没有rs.next不能使用rs.getXXX,报错(SQLException:Before start of result set)
2、mybatis only
①po、mapper.java、mapper.xml
②mybatis-mapper.xml
使用:String resource = "mybatis/mybatis-mapper.xml";InputStream is = demo02.class.getClassLoader().getResourceAsStream(resource);SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);SqlSession session = factory.openSession();String statement = "com.ytud.provider.mybatis.mapper.ProjectMapper.selectByPrimaryKey";int del = session.delete(statement);System.out.println(del);Project project = session.selectOne(statement, 2);System.out.println(project.getProjName());
3、mybatis+spring
applicationContext.xml
classpath:jdbc.properties
2 35 6 39 40 417 8 9 10 11 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 42 46 4743 44 45 48 49 50
测试代码: //JUnitpublic class test1 { private ProjectApiImpl projectApiImpl; @Before public void before() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); projectApiImpl = (ProjectApiImpl) ac.getBean("projectApiImpl"); } @Test public void test1() { ProjectModel project = projectApiImpl.getProject(1); System.out.println(project.getProjectName()); }}//spring提供JUnit测试框架@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"classpath:applicationContext.xml"})public class Demo02 { @Resource private ProjectApiImpl projectApiImpl; @Test public void test1() { ProjectModel project = projectApiImpl.getProject(1); System.out.println(project.getProjectName()); }}
4、mybatis+spring+spring mvc
web.xmlorg.springframework.web.context.ContextLoaderListener contextConfigLocation classpath:applicationContext.xml mvc-dispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:mvc-servlet-config.xml 1 mvc-dispatcher / characterEncodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 forceEncoding true characterEncodingFilter /*
5、mybatis+spring+spring mvc+dubbox