用Java写的My SQL操作封装类

 

Kagula

2009-11-17

 

关键词

    Java My SQL

 

概要:

    My SQL操作封装的Java源码示例。

 

要求环境:

    J2SE1.5 + Eclipse3.4.2

 

正文:

先到网上下载mysql-connector-java-5.0.8-bin.jar,并把它放到你的Java ProjectUser Library路径中。

下面是CMySQL的源码清单,具体如何使用,参考CMySQLmain方法。

 

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class CMySQL { private Connection conn; public CMySQL(String sWhere,String sAccount,String sPWD) { connect(sWhere,sAccount,sPWD); } public void finalize() { shutdown(); } private void connect(String sWhere,String sAccount,String sPWD) { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection(sWhere,sAccount,sPWD); }catch(Exception ex) { ex.printStackTrace(); } } public boolean executeUpdate(String strSQL) { boolean bR=true; try{ Statement stmt = conn.createStatement(); stmt.executeUpdate(strSQL); }catch(SQLException ex) { ex.printStackTrace(); bR=false; } return bR; } public List<Map<String,String>> executeQuery(String strSQL) { List<Map<String,String>> list=new ArrayList<Map<String,String>>(); ResultSet rs; try{ Statement stmt = conn.createStatement(); rs = stmt.executeQuery(strSQL); if(rs.next()) { ResultSetMetaData rsm = rs.getMetaData(); List<String> colNames = new ArrayList<String>(); for(int i=1;i<=rsm.getColumnCount();i++) colNames.add(rsm.getColumnName(i)); do{ Map<String,String> map=new HashMap<String,String>(); for(Iterator<String> it=colNames.iterator();it.hasNext();) { String colName=it.next(); map.put(colName, rs.getString(colName)); } list.add(map); }while(rs.next()); rs.close(); } }catch(SQLException ex) { ex.printStackTrace(); } return list; } public void testResult(List<Map<String,String>> list) { for(Iterator<Map<String,String>> it=list.iterator();it.hasNext();) { System.out.println(it.next()); } } private void shutdown() { try { conn.close(); }catch(SQLException ex) { ex.printStackTrace(); } } public static void main(String args[]) { try { //step1:test open&close CMySQL db=new CMySQL("jdbc:mysql://localhost:3306/mysql", "root", "12345678"); //step2:test query with return List<Map<String,String>> list=db.executeQuery("select * from babywatch"); db.testResult(list); //step3:test query with no return Map<String,String> map=list.get(0); db.executeUpdate("UPDATE babywatch SET LastTime = NOW() WHERE babywatch_id = " + map.get("babywatch_id").toString()); }catch(Exception ex) { ex.printStackTrace(); } } }

 

你可能感兴趣的:(java,sql,exception,String,list,query)