这是一个通用的javaBean,能够很方便的实现连接数据库、查询、插入、修改功能。
package com.common;
import java.sql.*;
public class DataBaseConn {
public Connection conn = null;
public void createConn(){
String DRIVER = "org.gjt.mm.mysql.Driver";
String url="jdbc:mysql://localhost/xin126?user=root&password=789456&useUnicode=true&characterEncoding=GB2312";
if(conn == null){
try{
Class.forName(DRIVER).newInstance();
conn = DriverManager.getConnection(url);
}catch(Exception e){
e.printStackTrace();
}
}
}
public Connection getConn(){
if(conn == null){
createConn();
}
return conn;
}
public void closeConn(){
if(conn != null){
try {
conn.close();
conn = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public ResultSet executeQuery(String sql) {
ResultSet rs = null;
if (conn == null) {
createConn();
}
try {
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
if (conn == null) {
createConn();
}
try {
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
stmt.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
import java.sql.*;
public class DataBaseConn {
public Connection conn = null;
public void createConn(){
String DRIVER = "org.gjt.mm.mysql.Driver";
String url="jdbc:mysql://localhost/xin126?user=root&password=789456&useUnicode=true&characterEncoding=GB2312";
if(conn == null){
try{
Class.forName(DRIVER).newInstance();
conn = DriverManager.getConnection(url);
}catch(Exception e){
e.printStackTrace();
}
}
}
public Connection getConn(){
if(conn == null){
createConn();
}
return conn;
}
public void closeConn(){
if(conn != null){
try {
conn.close();
conn = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public ResultSet executeQuery(String sql) {
ResultSet rs = null;
if (conn == null) {
createConn();
}
try {
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
if (conn == null) {
createConn();
}
try {
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
stmt.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
}