Leg*_*cks 2 java mysql servlets jdbc
我在Netbeans 7.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();
}
Run Code Online (Sandbox Code Playgroud)
小智 7
这个简单的方法怎么样?!
java.sql.Driver d=new com.mysql.jdbc.Driver();
Run Code Online (Sandbox Code Playgroud)
我也想知道你为什么用这种方式连接到数据库?!让服务器管理它会更好.
首先配置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>
Run Code Online (Sandbox Code Playgroud)
然后,简单地从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();
}
Run Code Online (Sandbox Code Playgroud)
顺便说一下,不要忘记在<CATALINA_BASE>/lib文件夹中编写MySQL JDBC驱动程序jar 文件.
| 归档时间: |
|
| 查看次数: |
39965 次 |
| 最近记录: |