那么这个简单的方法呢?
java.sql.Driver d=new com.MysqL.jdbc.Driver();
我也想知道为什么您要用这种方式连接数据库?最好让服务器对其进行管理。
首先context.xml像这样配置(如果您使用的是tomcat):
<context><Resource name='_ds' auth='Container' type='javax.sql.DataSource' maxActive='128' maxIdle='32' username='_admin' password='qwerty' driverClassName='com.MysqL.jdbc.Driver' url='jdbc:MysqL://127.0.0.1:3306/dbname'/></context>
然后,简单地从servlet / etc中的该资源获取连接,如下所示:
public void init() { try {_ds = (DataSource) InitialContext.lookup('java:/comp/env/_ds'); } catch (Exception ex) { }}private javax.sql.DataSource _ds;protected void doPost(HttpServletRequest request, HttpServletResponse response)throws servletexception, IOException{ try {/*String driver = 'com.MysqL.jdbc.Driver';con = null;String username = '';String password = '';Class.forName('com.MysqL.jdbc.Driver').newInstance();con = DriverManager.getConnection('jdbc:MysqL://localhost:3306/dbname', 'root', 'password');*/Connection con=_ds.getConnection();Statement st = con.createStatement();ResultSet mar = st.executeQuery('SELECT * FROM table');Gson gson = new GsonBuilder().create();response.setContentType('application/json'); response.setCharacterEncoding('utf-8'); con.close(); } catch (sqlException e) {String message = e.getMessage(); }
顺便说一句,不要忘记在<CATALINA_BASE>/lib文件夹中编写MysqL JDBC驱动程序jar 文件。
解决方法我在Netbeans7.2上遇到此错误,它说ClassNotFoundexception和InstantationException。我真的在这个问题上陷入困境。请帮助我。
protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException { try {String driver = 'com.mysql.jdbc.Driver';con = null;String username = '';String password = '';Class.forName('com.mysql.jdbc.Driver').newInstance();con = DriverManager.getConnection('jdbc:mysql://localhost:3306/dbName','root','password');Statement st = con.createStatement();ResultSet mar = st.executeQuery('SELECT * FROM table');Gson gson = new GsonBuilder().create();response.setContentType('application/json'); response.setCharacterEncoding('utf-8'); } catch (SQLException e) {String message = e.getMessage(); }