欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-23 16:01:52
package dao; import java.sql.*; public class basedao { //oracle// private&...

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<parms.length;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());
 }
}