public Connection getConnection() {
String url = "jdbc:sqlserver://localhost:1433DatabaseName=TestDB"
java.sql.Connection con = null
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
String user = "sa"
String pwd = "123456"
con = java.sql.DriverManager.getConnection(url, user, pwd)
}
catch (Exception ex) {
ex.printStackTrace()
}
return con
}
以上代码是创建数据库连接的语句,在具体应用时调用这个方法就可以了。
1、首先明确一点,servlet就是一个继承自javax.servlet.http.HttpServlet的类。
2、范例:使用servlet连接数据库
package com.oracle.project.servletimport java.util.*
import java.io.*
import java.sql.*
import javax.servlet.*
import javax.servlet.http.*
import javax.servlet.annotation.*
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"
public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:ORACLEDB"
public static final String DBUSER = "scott"
public static final String PASSWORLD = "tiger"
private Connection conn = null
public Connection getConnection() {
try {
if(this.conn == null) {
Class.forName(DBDRIVER)
this.conn = DriverManager.getConnection(DBURL,DBUSER,PASSWORLD)
}
} catch(Exception e) {
e.printStackTrace()
}
return conn
}
@Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
PrintWriter out = response.getWriter()
out.println("<html>")
out.println("<body>")
out.println("<h1>" + this.getConnection() + "</h1>")
out.println("</body>")
out.println("</html>")
}
@Override
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
this.doGet(request,response)
}
}
// 纯java方法,建立连接,数据库名称为:TestDBpublic Connection getConnection() {
String url = "jdbc:sqlserver://localhost:1433DatabaseName=TestDB"
java.sql.Connection con = null
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
String user = "sa"
String pwd = "123456"
con = java.sql.DriverManager.getConnection(url, user, pwd)
}
catch (Exception ex) {
ex.printStackTrace()
}
return con
}
以上代码是创建数据库连接的语句,在具体应用时调用这个方法就可以了。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)