标题:数据库连接的小问题
取消只看楼主
新手上路了
Rank: 1
等 级:新手上路
威 望:2
帖 子:107
专家分:0
注 册:2008-3-27
结帖率:100%
 问题点数:0 回复次数:0 
数据库连接的小问题
package dao;

import *;
import *;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * 加载驱动
 */
public class Driver extends HttpServlet {
   
    /**
    初始化数据库的驱动参数
    */
    private String driverClass;
    private String url;
    private String user;
    private String password;
   @Override
    public void init()
    {
        driverClass=getInitParameter("driverClass");
        url=getInitParameter("url");
        user=getInitParameter("user");
        password= getInitParameter("password");
    }

    public String getDriverClass() {
        return driverClass;
    }

    public String getUrl() {
        return url;
    }

    public String getUser() {
        return user;
    }

    public String getPassword() {
        return password;
    }
   
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */

public class DBUtil {
   Driver driver = new Driver();
   private Connection conn = null;
  DBUtil()
  {
     if(conn==null){
        try {
      
            Class.forName(driver.getDriverClass());
            conn=DriverManager.getConnection(driver.getUrl(),driver.getUser(),driver.getPassword());
        } catch (Exception ex) {
            Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);
          }
    }
  }
  public Connection getConnection()
  {
    return conn;
  }
      
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import dao.DBUtil;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class Test {
    public static void main(String args[])
    {

            DBUtil db = new DBUtil();
            try {

                java.sql.PreparedStatement ps = db.getConnection().prepareStatement("insert into class(name) values (?)");
                ps.setString(1, "张三");
                ps.executeUpdate();
                ps.close();
            } catch (SQLException ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
}
为什么会插不进去 说有空指针
搜索更多相关主题的帖子: 数据库 
2008-05-01 11:39



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-211879-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 2.848345 second(s), 10 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved