当前位置:数据库 > MySQL >>

jsp连接mysql数据库

把mysql-connector-java-5.1.18-bin.jar导入工程后运行还是出现java.lang.ClassNotFoundException:com.mysql.jdbc.driver 下面是我的代码<%@ page contentType="text/html;charset=utf-8"%><%@ page import="java.sql.*"%><html><% try{ Class.forName("com.mysql.jdbc.driver").newInstance(); String url="jdbc:mysql://localhost//company"; Connection conn=DriverManager.getConnection(url,"root","12345"); Statement stmt=conn.createStatement(); %><body><table border=1 cellspacing=1><tr><td>firstname</td><td>lastname</td><td>age</td><td>address</td><td>city</td></tr><% String sql="select * from employee" ; ResultSet rs=stmt.executeQuery(sql); while(rs!=null&&rs.next()) {out.print("<tr><td>"+ rs.getString("firstname")+"</td>"); out.print("<td>"+rs.getString("lastname") + "</td>") ; out.print("<td>"+rs.getInt("age")+"</td>"); out.print("<td>"+rs.getString("address")+"</td>") ; out.print("<td>"+rs.getString("city")+"</td></tr>"); } %></table></body><% rs.close(); stmt.close(); conn.close(); } catch(ClassNotFoundException cnfe) {out.print(cnfe);} catch(SQLException sqle) {out.print(sqle);} catch(Exception e) {out.print(e) ;}</html>没有网 手机写的 错别字见谅啊
答案:做两步应该就可以了:
1、在项目中右击--》build path-->add external archies-->找到你的jar包
2、复制你的jar包,粘贴到你的eclipse项目中WebRoot-->WEB-INF-->lib中就可以了。
试试吧。
其他:连接数据库的代码为了便于复用,你可以另外再写一个文件,把连接的代码放进去,比如你另一个文件叫做DbConnection.java,你把这个文件放到新建的一个包里。那么该文件下连接数据库就能这么做: 
public class DBConn { 
private String driver="com.mysql.jdbc.Driver";//mysql的驱动程序 
// allowMultiQueries=true 允许数据库一次执行多条sql语句 
// 在url中加入characterEncoding=gb2312可以解决mysql数据库的中文查询和插入问题 
private String url="jdbc:mysql://localhost/DatabaseName?characterEncoding=gb2312&allowMultiQueries=true";//DatabaseName是你的数据库的名字 
private String user="root";//mysql数据库的用户名 
private String password="123456";//密码 
private Connection conn=null; 
private Statement stmt=null; 

/** 
* 在构造函数中连接数据库 
*/ 
public DBConn(){ 
try{ 
Class.forName(driver); 
conn=DriverManager.getConnection(url,user,password); 
}catch(Exception e){ 
System.out.println(e.toString()); 
} 
} 
} 
这个函数是通用的,另外,你要执行查询、删除、增加等操作,也可以把这些增删查改的函数写在这个文件下面。
使用的时候就是在jsp页面用import引入,<import id="dbConn" class="包名.DbConnection">
然后用dbConn写就行。如果还不能理解,建议你查看一下相关的资料,就不是你写连接数据库的问题了。 在jsp里可以这样连接上数据库,这已经是最简单的了:
以MySQL为例:
<%
Class.forName("com.mysql.jdbc.Driver"); 
 String url="jdbc:mysql://localhost:3306/你的数据库名称?user=root&password=";
 Connection conn= DriverManager.getConnection(url); 
 Statement stmt=conn.createStatement();
 request.setCharacterEncoding("gb2312");

 String sql="select * from 你的数据库表"; 
 ResultSet rs=stmt.executeQuery(sql);
%>
注意上面代码中user是你登录数据库的用户名,password是你登录数据库的密码。 

上一个:mysql 建表int(10,4)是什么意思
下一个:mysql 远程连接

Oracle
MySQL
Access
SQLServer
DB2
Excel
SQLite
SYBASE
Postgres
如果你遇到数据库难题:
请访问www.zzzyk.com 试试
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,