数据库操作类

写下一个简单的常用数据库操作类,以方便以后使用。(注:数据库连接驱动 在附件下载中)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBUtils {

	private Connection conn;
	//private String url = "jdbc:sqlserver://127.0.0.1:1433;user=sa;password=123;database=DB2";//SqlServer数据库连接
	private String url = "jdbc:mysql://localhost/test?user=root&password=123";     //MySql数据库连接

	/**
	 * 构造函数
	 * */
	DBUtils() {
		try {
			//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");   //SqlServer
			Class.forName("com.mysql.jdbc.Driver");                            //MySql
			conn = DriverManager.getConnection(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
//odbc连接
        public Connection getConnAccess() {
		String url = "jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=C:\\少儿电子书.mdb";
		Connection con = null;
		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			con = DriverManager.getConnection(url, "", "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}
	/**
	 * 返回 PreparedStatement对象
	 *  @param sqlString 要执行的sql语句
	 * 
	 * */
	public PreparedStatement getPreStatement(String sqlString){
		PreparedStatement preStatement = null;
		try {
			preStatement = conn.prepareStatement(sqlString);
			return preStatement;
		} catch (SQLException e) {
			System.out.println("PreparedStatement对象创建失败!");
			return null;       //如果创建失败 返回Null
		}
	}
	
	
	/**
	 * 关闭数据库连接
	 * */
	public  void closeConn(){
		try {
			if(!conn.isClosed()){
				conn.close();
			}
		} catch (SQLException e) {
			System.out.println("数据库连接关闭过程中出错!");
		}
	}
	public static void main(String[] args) throws Exception{
		DBUtils db = new DBUtils();
		String sql  = "insert into dbtest( title) values(?)";
		PreparedStatement st = db.getPreStatement(sql);
		st.setString(1, "中国的第四件大事儿");
		st.addBatch();
		st.execute();
                //各种关闭 省略...
 }
}								



												

猜你喜欢

转载自mumaqm.iteye.com/blog/1597915