How to using Servlet to connect to MS SQL Server with DSN?

Dear all,A want to sue servlet to connect to MS SQL server 2000 with DSN, how to code it? Help me please, i'm just a beginner to use java to develop application, hope that i can have your reply soon, as it's really quite urgentGalaxia
[264 byte] By [galaxia] at [2007-9-26 4:35:00]
# 1

Connecting to MS SQL Server using servlets does not differ from you do usually:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Connection conn = null;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException ex) {

}

try {

conn = DriverManager.getConnection(

"jdbc:odbc:" + yourDSN,

userName,

password);

} catch(SQLException ex) {

}

response.setContentType("text/html");

PrintWriter out = new PrintWriter(response.getOutputStream());

// create statements, get resultSet's and write the

// output to the client.

Statement stm = con.createStatement(

"select * from myTable"

)

stm.execute();

ResultSet rs = stm.getResultSet();

// print headers

out.println("<table><tr>")

out.println("<td>One column</td>")

out.println("</tr></table>")

while(rs.next()) {

// print rows

out.println("<tr>")

out.println("<td>" + rs.getString(1) + "</td>")

out.println("</tr>")

}

try {

conn.close();

} catch(SQLException ex) {

}

}

llturro at 2007-6-29 17:51:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 2

import java.io.*;

import java.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class YourServlet extends HttpServlet

{

public void doGet/doPost(HttpServletRequest req,HttpServletResponse res)

{

res.setContentType("text/html");

PrintWriter out=res.getWriter();

try

{

Connection con=getConnection();

// do what ever u like

}catch(SQLException sqle){out.println(sqle);}

}

private Connection getConnection()

{

Connection con=null;

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:"+yourDsn,user,password);

}catch(ClassNotFoundException cnfe){}

catch(SQLException sqle){}

return con;

}

}

parul_patidar at 2007-6-29 17:51:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...