工程与数据库同上一节:http://blog.csdn.net/u011179993/article/details/47294875
新建下图中红色方框内两个类
package com.jazz.study2; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.junit.*; public class TestSta { Connection conn = null; Statement sta = null; ResultSet rs = null; @Before public void before() throws Exception { String diverName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/jdbcstudy"; String user = "root"; String password = "123456"; Class.forName(diverName); conn = DriverManager.getConnection(url, user, password); sta = conn.createStatement(); } @Test public void testInsert() throws SQLException { int num = sta.executeUpdate("insert into user(id,name,password,phone) values(3,'小精灵','qwer','145677')"); if (num > 0) System.out.print("插入成功!"); else System.out.print("插入失败!"); } @Test public void testUpdate() throws SQLException { int num = sta.executeUpdate("update user set name='剑圣' where id=3"); if (num > 0) System.out.print("更新成功!"); else System.out.print("更新失败!"); } @Test public void testDel() throws SQLException { int num = sta.executeUpdate("delete from user where id=3"); if (num > 0) System.out.print("删除成功!"); else System.out.print("删除失败!"); } @After public void after() throws Exception { if (rs != null) rs.close(); if (sta != null) sta.close(); if (conn != null) conn.close(); } }
package com.jazz.study2; import java.sql.*; import org.junit.*; public class TestPreparedSta { Connection conn = null; PreparedStatement psta = null; ResultSet rs = null; @Before public void before() throws Exception { String diverName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/jdbcstudy"; String user = "root"; String password = "123456"; Class.forName(diverName); conn = DriverManager.getConnection(url, user, password); } @Test public void testInsert() throws Exception { psta=conn.prepareStatement("insert into user(id,name,password,phone) values(3,?,?,'13244441414')"); psta.setString(1, "死亡先知"); psta.setString(2, "44444"); int num = psta.executeUpdate(); if (num > 0) System.out.print("插入成功!"); } @Test public void testUpdate() throws SQLException { psta=conn.prepareStatement("update user set name=? where id=3"); psta.setString(1, "巫医"); //psta.setInt(2, 3); int num = psta.executeUpdate(); if (num > 0) System.out.print("更新成功!"); } @Test public void testDel() throws SQLException { psta=conn.prepareStatement("delete from user where id=?"); psta.setInt(1, 3); int num=psta.executeUpdate(); if (num > 0) System.out.print("删除成功!"); } @Test public void testSelect() throws SQLException { psta=conn.prepareStatement("select name from user where id<?"); psta.setInt(1, 4); rs=psta.executeQuery(); while(rs.next()){ System.out.println(rs.getString("name")); } } @After public void after() throws Exception { if (rs != null) rs.close(); if (psta != null) psta.close(); if (conn != null) conn.close(); } }