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<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());
}
}
上一篇: Java四种线程池的使用详解
下一篇: 加快JDBC设计中JSP访问数据库