js|程序|数据|数据库|数据库连接
package online;
import java.sql.*;
public class DBConn {
private static String rootpath = "web发布路径";
private String sample = "sample";
private Connection con = null;
private Statement stmt = null;
ResultSet rs = null;
/***************************************************************/
private static final String DRIVE = "sun.jdbc.odbc.JdbcOdbcDriver";
//暂时使用jdbc-odbc连接//"com.microsoft.jdbc.sqlserver.SQLServerDriver";
private static final String USERNAME = "sa";
private static final String PASSWORD = "123aaa";
private static final String HOST = "http:127.0.0.1:8080/renshi";
/*************************************************************/
//暂时使用jdbc-odbc数据源
private static final String CONNECTION_STRING = "jdbc:odbc:renshi";
//"jdbc:microsoft:sqlserver://localhost;1433;";
public static String getRootPath() {
return rootpath;
}
public DBConn() { //加载驱动
try {
Class.forName(DRIVE);
}
catch (ClassNotFoundException e) {
System.err.println("DBConn():" + e.toString());
}
catch (Exception e) {
System.err.println("DBConn():" + e.toString());
}
}
public Connection getConnection() { //得到连接
try {
String strUrl = CONNECTION_STRING;
/***********周五晚改动****************************************/
//+ "DatebaseName=renshi," + USERNAME +"," + PASSWORD;
con = DriverManager.getConnection(strUrl, this.USERNAME, this.PASSWORD);
}
catch (Exception e) {
con = null;
}
return con;
}
public void dropConnection() { //关闭连接
try {
closeStmt();
con.close();
}
catch (Exception ignored) {
}
finally {
con = null;
}
}
public ResultSet executeQuery(String sql) { //执行sql查询
ResultSet rs = null;
try {
con = getConnection();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
}
catch (SQLException ex) {
System.err.println("DBConn.executeQuery():" + ex.getMessage());
}
return rs;
}
public int executeUpdate(String sql) { //执行sql更新语句
int i=0;
stmt = null;
rs = null;
try {
con = getConnection();
stmt = con.createStatement();
i= stmt.executeUpdate(sql);
stmt.close();
con.close();
}
catch (SQLException ex) {
System.err.println("DBConn:executeUpdate(0:" + ex.getMessage());
}
return i;
}
public void execute(String sql) { //执行sql语句
stmt = null;
rs = null;
try {
con = getConnection();
stmt = con.createStatement();
stmt.execute(sql);
stmt.close();
con.close();
}
catch (SQLException ex) {
System.err.println("DBConn:excute():" + ex.getMessage());
}
}
public void closeConn() { //关闭sql连接
try {
stmt.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
public void closeStmt() { //关闭sql连接
try {
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
/**
* main
*/
public static void main(String[] args) throws SQLException {
DBConn one=new DBConn();
ResultSet rs=one.executeQuery("select * from PS_INFO");
while(rs.next()){
System.out.println(rs.getString(2));
}
}
}