package util;
/*
* date: 2004-11-17
* author:zhangyu6050;
* todo: 一个数据库封装类,作用是:
* 获取数据库连接
* 通过接受的SQL语句选择数据库并且返回结果
* 期间要作出以下判断:1 如果sql用来查询:、、、、
* 2 如果sql用来update:、、、、
*
* bugs:
* 改进:实现接口:sqlQuery;
* 主要继承一些比如ERROR,SUCCESS等的常量!
*/
//package util;
import java.util.List;
import java.sql.*;
public class Mysql {
private String dirverName=Configs.dirverName;
private String URL=Configs.URL;
private String password=Configs.password;
private String userName=Configs.userName;
private Connection conn = null;
private Statement stmt = null;
private PreparedStatement prepstmt = null;
public Mysql(){
try {
getDataSource();
stmt=conn.createStatement();
} catch (SQLException e) {
System.out.print("conn.createStatement()发生错误!");
e.printStackTrace();
}
}
public Mysql(String query){
init(query);
}
protected void init(String aqurey){
try {
stmt=conn.createStatement();
prepareStatement(aqurey);
} catch (SQLException e) {
System.out.print("conn.createStatement()发生错误!");
e.printStackTrace();
}
}
//这个方法是准备创建一个MYsql对象后再调用,但我发现最好用单态从新设计!!!!改成静态方法
//设置?为变量的值--string类型
public void setString(int index, String value) throws SQLException {
prepstmt.setString(index, value);
}
public void prepareStatement(String sql) throws SQLException {
prepstmt = conn.prepareStatement(sql);
}
public void close() throws SQLException{
if(prepstmt!=null) prepstmt.close();
if(stmt!=null) prepstmt.close();
}
public ResultSet executeQuery() throws SQLException {
if (prepstmt != null) {
return prepstmt.executeQuery();
} else
return null;
}
public void getDataSource(){
try {
Class.forName(dirverName);
conn=DriverManager.getConnection(URL,userName,password);
} catch (Exception e) {
//连接发生错误!
System.out.print("连接发生错误!");
e.printStackTrace();
}
}
}