java使用jdbc操作数据库示例分享

package dao;

import java.sql.*;

public class BaseDao {

 //oracle
// private  static final String Dirver="oracle.jdbc.driver.OracleDriver";
// private  static final String URL="jdbc:oracle:thin:@localhost:1521:XE";
// private  static final String name="admin";
// private  static final String pass="123";

 //sqlserver
// private static final String Dirver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
// private static final String URL="jdbc:sqlserver://localhost:1433;DatabaseName=TBLdb";
// private static final String name="sa";
// private static final String pass="sa";

 //mysql
 private static final String Dirver="com.mysql.jdbc.Driver";
 private static final String URL="jdbc:mysql://127.0.0.1:3306/school";
 private static final String name="root";
 private static final String pass="123456";

 public  Connection getCconnection()
 {
  Connection conn=null;
  try {
   Class.forName(Dirver);
   conn=DriverManager.getConnection(URL,name,pass);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return conn;
 }
 public void closAll(Connection conn,PreparedStatement ps,ResultSet rs)
 {
  try {
   if(null!=rs)
    rs.close();
   if(null!=ps)
    ps.close();
   if(null!=conn)
    conn.close();
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 public int executeUpdate(String sql,String parms[])
 {
  Connection conn=null;
  PreparedStatement ps=null;
  int result=-1;
  try {
   conn=getCconnection();
   ps=conn.prepareStatement(sql);
   if(null!=parms){
    for(int i=0;i     ps.setString(i+1,parms[i]);
    }
   }
   result=ps.executeUpdate();
   execute();

  } catch (Exception e) {
   System.out.println(e.getMessage());
  }finally{
   closAll(conn, ps, null);
  }
  return result;
 }
  public static void main(String[] args)throws Exception
 {
  BaseDao b=new BaseDao();
  Connection con=b.getCconnection();
  System.out.println(con.isClosed());
 }
}

你可能感兴趣的:(java使用jdbc操作数据库示例分享)