JDBC增刪改查方法小記(2個表相關聯)
阿新 • • 發佈:2018-11-09
第一個類引用http://blog.csdn.net/bhq2010/article/details/7478659
SingletonConn類:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import org.springframework.core.io.support.PropertiesLoaderUtils; public class SingletonConn { private Connection connection = null; private Statement statement = null; private ResultSet resultSet = null; private static String DBClassName = null; private static String DBUrl = null; private static String DBUser = null; private static String DBPassword = null; private static SingletonConn instance = null; protected SingletonConn() { } static { try { Properties props = PropertiesLoaderUtils.loadAllProperties("com/ioif/wha/database/database.properties"); DBClassName = props.getProperty("DriverClass"); DBUrl = props.getProperty("URL"); DBUser = props.getProperty("User"); DBPassword = props.getProperty("Password"); Class.forName(DBClassName); } catch (Exception e) { e.printStackTrace(); } } public static synchronized SingletonConn getInstance() { if(instance == null) { instance = new SingletonConn(); } return instance; } public synchronized Connection getConnection() throws SQLException { //僅當connection失效時才重新獲取 if (connection == null || connection.isValid(10) == false) { connection = DriverManager.getConnection(DBUrl, DBUser, DBPassword); } return connection; } private synchronized void getStatement() throws SQLException { getConnection(); //僅當statement失效時才重新建立 if (statement == null || statement.isClosed() == true) { statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); } } public synchronized void close() throws SQLException { if (resultSet != null) { resultSet.close(); resultSet = null; } if (statement != null) { statement.close(); statement = null; } if (connection != null) { connection.close(); connection = null; } } public synchronized ResultSet executeQuery(String sql) throws SQLException { getStatement(); if (resultSet != null && resultSet.isClosed() == false) { resultSet.close(); } resultSet = null; resultSet = statement.executeQuery(sql); return resultSet; } public synchronized int executeUpdate(String sql) throws SQLException { int result = 0; getStatement(); result = statement.executeUpdate(sql); return result; } }
DBUtil類:
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import com.ioif.wha.database.Data; public class DBUtill { Data d; static List<Data> list = new ArrayList<Data>(); static String tabName; private static Connection conn = null; private static PreparedStatement ps = null; public static List getDate() { list.clear(); try { ResultSet rs = SingletonConn .getInstance() .executeQuery( "select * from vav_page page,vav_card card where page.id=card.id"); while (rs.next()) { int id = rs.getInt("id"); int type = rs.getInt("type"); int position = rs.getInt("position"); String name = rs.getString("name"); String url = rs.getString("url"); String imageUrl = rs.getString("imageUrl"); System.out.println("id---" + id + "---position---" + position + "---type---" + type + "---name---" + name + "---url---" + url + "---imageurl---" + imageUrl); Data d = new Data(id, position, type, name, url, imageUrl); list.add(d); } } catch (Exception e) { e.printStackTrace(); } return list; } public static boolean creatTable() { boolean flag = false; if (tabName == null || tabName.equals("")) { return false; } System.out.println("Creating tables..."); String sql = "CREATE TABLE " + tabName + "_page " + "( id INTEGER auto_increment not null, " + " position INTEGER, " + " type INTEGER, " + " PRIMARY KEY( id ))"; String sql2 = "CREATE TABLE " + tabName + "_card" + "(" + "id INTEGER auto_increment NOT NULL, " + "name VARCHAR(255), " + "url VARCHAR(255), " + "imageUrl VARCHAR(255)," + "PRIMARY KEY(id), " + "constraint fk_" + tabName + " foreign key(id) references " + tabName + "_page(id)" + ")"; try { SingletonConn.getInstance().executeUpdate(sql); SingletonConn.getInstance().executeUpdate(sql2); System.out.println("Created tables..."); flag = true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return flag; } public static List getTabName() { List<String> list = new ArrayList<String>(); List<String> listWithoutDup; // 獲取表名 ResultSet rs; try { rs = SingletonConn.getInstance().getConnection().getMetaData() .getTables("", "", "", null); while (rs.next()) { String Name = rs.getString("TABLE_NAME"); int i = Name.indexOf("_"); String tbName = Name.substring(0,i); System.out.println(tbName); list.add(tbName); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } listWithoutDup = new ArrayList<String>(new HashSet<String>(list)); return listWithoutDup; } public static void setTabName(String Name) { tabName = Name; } public static boolean InsertDate(List<Data> list) { boolean flag = false; System.out.println("Inserting tables..."); if (tabName == null || tabName.equals("")) { return false; } try { conn = SingletonConn.getInstance().getConnection(); conn.setAutoCommit(false); for (int i = 0; i < list.size(); i++) { int positon = list.get(i).getPosition(); int type = list.get(i).getType(); String name = list.get(i).getName(); String url = list.get(i).getUrl(); String imageUrl = list.get(i).getImageUrl(); String sql = "insert into " + tabName + "_page(position,type) values(?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, positon); ps.setInt(2, type); ps.executeUpdate(); sql = "select id from "+tabName+"_page where position=? and type =?"; ps = conn.prepareStatement(sql); ps.setInt(1, positon); ps.setInt(2, type); ResultSet rs = ps.executeQuery(); int id = 0; while(rs.next()){ id = rs.getInt("id"); } sql = "insert into " + tabName + "_card(id,name,url,imageUrl) values(?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, id); ps.setString(2, name); ps.setString(3, url); ps.setString(4, imageUrl); ps.executeUpdate(); ps.close(); conn.commit(); } System.out.println("Inserted tables..."); flag = true; } catch (SQLException e) { // TODO Auto-generated catch block try { conn.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } return flag; } public static boolean Update(Data data){ boolean flag = false; System.out.println("Updating tables..."); if (tabName == null || tabName.equals("")) { return false; } try{ conn = SingletonConn.getInstance().getConnection(); String sql = "update "+tabName+"_page set position=?,type=? where id=?"; ps = conn.prepareStatement(sql); ps.setInt(1, data.getPosition()); ps.setInt(2, data.getType()); ps.setInt(3, data.getId()); ps.executeUpdate(); ps.close(); sql = "update "+tabName+"_card set name=?,url=?,imageUrl=? where id=?"; ps = conn.prepareStatement(sql); ps.setString(1, data.getName()); ps.setString(2, data.getUrl()); ps.setString(3, data.getImageUrl()); ps.setInt(4, data.getId()); ps.executeUpdate(); ps.close(); conn.commit(); System.out.println("Updated tables..."); flag = true; }catch(Exception e){ try { conn.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } return flag; } public static boolean Delete(int id){ boolean flag = false; System.out.println("Deleting tables..."); if (tabName == null || tabName.equals("")) { return false; } try{ String sql = "delete from "+tabName+"_card where id="+id; SingletonConn.getInstance().executeUpdate(sql); sql = "delete from "+tabName+"_page where id="+id; SingletonConn.getInstance().executeUpdate(sql); System.out.println("Deleted tables..."); flag = true; }catch(Exception e){ e.printStackTrace(); } return flag; } }