goldedge 发表于 2003-10-21 09:59:21

JSP连接数据库大全

现在有好多初学jsp的网友经常会问数据库怎么连接啊,怎么老出错啊?所以我集中的在这写篇文章供大家参考,其实这种把数据库逻辑全部放在jsp里未必是好的做法,但是有利于初学者学习,所以我就这样做了,当大家学到一定程度的时候,可以考虑用MVC的模式开发。在练习这些代码的时候,你一定将jdbc的驱动程序放到服务器的类路径里,然后要在数据库里建一个表test,有两个字段比如为test1,test2,可以用下面SQL建
create table test(test1 varchar(20),test2 varchar(20)
然后向这个表写入一条测试纪录
那么现在开始我们的jsp和数据库之旅吧。
一、jsp连接Oracle8/8i/9i数据库(用thin模式)
testoracle.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
&lt;%Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url="jdbc:oracle:thin:@localhost:1521:orcl";
//orcl为你的数据库的SID
String user="scott";
String password="tiger";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%&gt;
您的第一个字段内容为:&lt;%=rs.getString(1)%&gt;
您的第二个字段内容为:&lt;%=rs.getString(2)%&gt;
&lt;%}%&gt;
&lt;%out.print("数据库操作成功,恭喜你");%&gt;
&lt;%rs.close();
stmt.close();
conn.close();
%&gt;
</body>
&lt;/html&gt;
二、jsp连接Sql Server7.0/2000数据库
testsqlserver.jsp如下:
&lt;%@ page contentType="text/html;charset=gb2312"%&gt;
&lt;%@ page import="java.sql.*"%&gt;
&lt;html&gt;
<body>
&lt;%Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
//pubs为你的数据库的
String user="sa";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%&gt;
您的第一个字段内容为:&lt;%=rs.getString(1)%&gt;
您的第二个字段内容为:&lt;%=rs.getString(2)%&gt;
&lt;%}%&gt;
&lt;%out.print("数据库操作成功,恭喜你");%&gt;
&lt;%rs.close();
stmt.close();
conn.close();
%&gt;
</body>
&lt;/html&gt;
三、jsp连接DB2数据库
testdb2.jsp如下:
&lt;%@ page contentType="text/html;charset=gb2312"%&gt;
&lt;%@ page import="java.sql.*"%&gt;
&lt;html&gt;
<body>
&lt;%Class.forName("com.ibm.db2.jdbc.app.DB2Driver").newInstance();
String url="jdbc:db2://localhost:5000/sample";
//sample为你的数据库名
String user="admin";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%&gt;
您的第一个字段内容为:&lt;%=rs.getString(1)%&gt;
您的第二个字段内容为:&lt;%=rs.getString(2)%&gt;
&lt;%}%&gt;
&lt;%out.print("数据库操作成功,恭喜你");%&gt;
&lt;%rs.close();
stmt.close();
conn.close();
%&gt;
</body>
&lt;/html&gt;
四、jsp连接Informix数据库
testinformix.jsp如下:
&lt;%@ page contentType="text/html;charset=gb2312"%&gt;
&lt;%@ page import="java.sql.*"%&gt;
&lt;html&gt;
<body>
&lt;%Class.forName("com.informix.jdbc.IfxDriver").newInstance();
String url =
"jdbc:informix-sqli://123.45.67.89:1533/testDB:INFORMIXSERVER=myserver;
user=testuser;password=testpassword";
//testDB为你的数据库名
Connection conn= DriverManager.getConnection(url);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%&gt;
您的第一个字段内容为:&lt;%=rs.getString(1)%&gt;
您的第二个字段内容为:&lt;%=rs.getString(2)%&gt;
&lt;%}%&gt;
&lt;%out.print("数据库操作成功,恭喜你");%&gt;
&lt;%rs.close();
stmt.close();
conn.close();
%&gt;
</body>
&lt;/html&gt;
五、jsp连接Sybase数据库
testmysql.jsp如下:
&lt;%@ page contentType="text/html;charset=gb2312"%&gt;
&lt;%@ page import="java.sql.*"%&gt;
&lt;html&gt;
<body>
&lt;%Class.forName("com.sybase.jdbc.SybDriver").newInstance();
String url ="jdbc:sybase:Tds:localhost:5007/tsdata";
//tsdata为你的数据库名
Properties sysProps = System.getProperties();
SysProps.put("user","userid");
SysProps.put("password","pass");
Connection conn= DriverManager.getConnection(url, SysProps);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%&gt;
您的第一个字段内容为:&lt;%=rs.getString(1)%&gt;
您的第二个字段内容为:&lt;%=rs.getString(2)%&gt;
&lt;%}%&gt;
&lt;%out.print("数据库操作成功,恭喜你");%&gt;
&lt;%rs.close();
stmt.close();
conn.close();
%&gt;
</body>
&lt;/html&gt;
六、jsp连接MySQL数据库
testmysql.jsp如下:
&lt;%@ page contentType="text/html;charset=gb2312"%&gt;
&lt;%@ page import="java.sql.*"%&gt;
&lt;html&gt;
<body>
&lt;%Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost/softforum?user=soft&amp;password=soft1234&amp;useUnicode=true&amp;characterEncoding=8859_1"
//testDB为你的数据库名
Connection conn= DriverManager.getConnection(url);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%&gt;
您的第一个字段内容为:&lt;%=rs.getString(1)%&gt;
您的第二个字段内容为:&lt;%=rs.getString(2)%&gt;
&lt;%}%&gt;
&lt;%out.print("数据库操作成功,恭喜你");%&gt;
&lt;%rs.close();
stmt.close();
conn.close();
%&gt;
</body>
&lt;/html&gt;
七、jsp连接PostgreSQL数据库
testmysql.jsp如下:
&lt;%@ page contentType="text/html;charset=gb2312"%&gt;
&lt;%@ page import="java.sql.*"%&gt;
&lt;html&gt;
<body>
&lt;%Class.forName("org.postgresql.Driver").newInstance();
String url ="jdbc:postgresql://localhost/soft"
//soft为你的数据库名
String user="myuser";
String password="mypassword";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%&gt;
您的第一个字段内容为:&lt;%=rs.getString(1)%&gt;
您的第二个字段内容为:&lt;%=rs.getString(2)%&gt;
&lt;%}%&gt;
&lt;%out.print("数据库操作成功,恭喜你");%&gt;
&lt;%rs.close();
stmt.close();
conn.close();
%&gt;
</body>
&lt;/html&gt;

jiangtao9999 发表于 2003-10-21 14:55:37

题外话:ASP的?!

goldedge 发表于 2003-10-22 17:11:54


题外话:ASP的?!



现在很多搞asp的都在转学jsp,所以........ :-)

不过我帮你找找

magicmao 发表于 2003-10-28 09:06:53

嗬嗬,我加一个连接可以access(中文查询)的:P

例:
g_drvSQL = &#40;Driver&#41;Class.forName&#40;MM_testjdbc_DRIVER&#41;.newInstance&#40;&#41;;;
g_connSQL = DriverManager.getConnection&#40;MM_testjdbc_STRING,MM_testjdbc_USERNAME,MM_testjdbc_PASSWORD&#41;;

String aszParam&#91;&#93; = {&quot;游客&quot;};
MyOpenResultset&#40;&quot;SELECT *FROM 注册用户列表 WHERE realname LIKE ?&quot;,aszParam&#41;;

返回的ResultSet为:
g_rstSQL




&lt;%!

// resultset
Driver g_drvSQL = null;
Connection g_connSQL = null;
PreparedStatement g_stmSQL = null;
ResultSet g_rstSQL = null;


public String MyGetColumn&#40;String str&#41; throws Exception{
Object objData;
objData = &#40;&#40;&#40;objData = g_rstSQL.getObject&#40;str&#41;&#41;==null || g_rstSQL.wasNull&#40;&#41;&#41;?&quot;&quot;&#58;objData&#41;;
return MyUnicode2Chinese&#40;objData.toString&#40;&#41;&#41;;
}

public String&#91;&#93; MyFormatsql&#40;ServletRequest request, String columns, String fields, int ntype&#41; throws Exception{
String aszReturn&#91;&#93; = {&quot;&quot;,&quot;&quot;};
String&#91;&#93; MM_fields = null, MM_columns = null;
try{
//get from form first
java.util.StringTokenizer tokens = new java.util.StringTokenizer&#40;fields,&quot;|&quot;&#41;;
MM_fields = new String&#91;tokens.countTokens&#40;&#41;&#93;;
for &#40;int i=0; tokens.hasMoreTokens&#40;&#41;; i++&#41; MM_fields&#91;i&#93; = tokens.nextToken&#40;&#41;;

tokens = new java.util.StringTokenizer&#40;columns,&quot;|&quot;&#41;;
MM_columns = new String&#91;tokens.countTokens&#40;&#41;&#93;;
for &#40;int i=0; tokens.hasMoreTokens&#40;&#41;; i++&#41; MM_columns&#91;i&#93; = tokens.nextToken&#40;&#41;;

// set the form values
for &#40;int i=0; i+1 &lt; MM_fields.length; i+=2&#41; {
   MM_fields&#91;i+1&#93; = &#40;&#40;request.getParameter&#40;MM_fields&#91;i&#93;&#41;!=null&#41;?&#40;String&#41;request.getParameter&#40;MM_fields&#91;i&#93;&#41;&#58;&quot;&quot;&#41;;
}

if &#40;0==ntype&#41;{
   StringBuffer buffer = new StringBuffer&#40;&#41;;
//update
// create the update sql statement
//MM_editQuery = new StringBuffer&#40;&quot;update &quot;&#41;.append&#40;MM_editTable&#41;.append&#40;&quot; set &quot;&#41;;
   for &#40;int i=0; i+1 &lt; MM_fields.length; i+=2&#41; {
    String formVal = MM_fields&#91;i+1&#93;;
    String elem;
    tokens = new java.util.StringTokenizer&#40;MM_columns&#91;i+1&#93;,&quot;,&quot;&#41;;
    String delim    = &#40;&#40;elem = &#40;String&#41;tokens.nextToken&#40;&#41;&#41; != null &amp;&amp; elem.compareTo&#40;&quot;none&quot;&#41;!=0&#41;?elem&#58;&quot;&quot;;
    String altVal   = &#40;&#40;elem = &#40;String&#41;tokens.nextToken&#40;&#41;&#41; != null &amp;&amp; elem.compareTo&#40;&quot;none&quot;&#41;!=0&#41;?elem&#58;&quot;&quot;;
    String emptyVal = &#40;&#40;elem = &#40;String&#41;tokens.nextToken&#40;&#41;&#41; != null &amp;&amp; elem.compareTo&#40;&quot;none&quot;&#41;!=0&#41;?elem&#58;&quot;&quot;;
    if &#40;formVal.length&#40;&#41; == 0&#41; {
      formVal = emptyVal;
    } else {
   if &#40;altVal.length&#40;&#41; != 0&#41; {
      formVal = altVal;
   } else if &#40;delim.compareTo&#40;&quot;'&quot;&#41; == 0&#41; {// escape quotes
      StringBuffer escQuotes = new StringBuffer&#40;formVal&#41;;
      for &#40;int j=0; j &lt; escQuotes.length&#40;&#41;; j++&#41;
       if &#40;escQuotes.charAt&#40;j&#41; == '\''&#41; escQuotes.insert&#40;j++,'\''&#41;;
      formVal = &quot;'&quot; + escQuotes + &quot;'&quot;;
   } else {
      formVal = delim + formVal + delim;
   }
    }
    buffer.append&#40;&#40;i!=0&#41;?&quot;,&quot;&#58;&quot;&quot;&#41;.append&#40;MM_columns&#91;i&#93;&#41;.append&#40;&quot; = &quot;&#41;.append&#40;formVal&#41;;
   }
   aszReturn&#91;0&#93; = buffer.toString&#40;&#41;;
}else if&#40;1==ntype&#41;{
//insert

StringBuffer MM_tableValues = new StringBuffer&#40;&#41;, MM_dbValues = new StringBuffer&#40;&#41;;
for &#40;int i=0; i+1 &lt; MM_fields.length; i+=2&#41; {
    String formVal = MM_fields&#91;i+1&#93;;
    String elem;
    tokens = new java.util.StringTokenizer&#40;MM_columns&#91;i+1&#93;,&quot;,&quot;&#41;;
    String delim    = &#40;&#40;elem = &#40;String&#41;tokens.nextToken&#40;&#41;&#41; != null &amp;&amp; elem.compareTo&#40;&quot;none&quot;&#41;!=0&#41;?elem&#58;&quot;&quot;;
    String altVal   = &#40;&#40;elem = &#40;String&#41;tokens.nextToken&#40;&#41;&#41; != null &amp;&amp; elem.compareTo&#40;&quot;none&quot;&#41;!=0&#41;?elem&#58;&quot;&quot;;
    String emptyVal = &#40;&#40;elem = &#40;String&#41;tokens.nextToken&#40;&#41;&#41; != null &amp;&amp; elem.compareTo&#40;&quot;none&quot;&#41;!=0&#41;?elem&#58;&quot;&quot;;
    if &#40;formVal.length&#40;&#41; == 0&#41; {
      formVal = emptyVal;
    } else {
      if &#40;altVal.length&#40;&#41; != 0&#41; {
      formVal = altVal;
      } else if &#40;delim.compareTo&#40;&quot;'&quot;&#41; == 0&#41; {// escape quotes
      StringBuffer escQuotes = new StringBuffer&#40;formVal&#41;;
      for &#40;int j=0; j &lt; escQuotes.length&#40;&#41;; j++&#41;
          if &#40;escQuotes.charAt&#40;j&#41; == '\''&#41; escQuotes.insert&#40;j++,'\''&#41;;
      formVal = &quot;'&quot; + escQuotes + &quot;'&quot;;
      } else {
      formVal = delim + formVal + delim;
      }
    }
    MM_tableValues.append&#40;&#40;i!=0&#41;?&quot;,&quot;&#58;&quot;&quot;&#41;.append&#40;MM_columns&#91;i&#93;&#41;;
    MM_dbValues.append&#40;&#40;i!=0&#41;?&quot;,&quot;&#58;&quot;&quot;&#41;.append&#40;formVal&#41;;
}

aszReturn&#91;0&#93; = MM_tableValues.toString&#40;&#41;;
aszReturn&#91;1&#93; = MM_dbValues.toString&#40;&#41;;

}
return aszReturn;
}catch&#40;Exception e&#41;{
return null;
}
}

public void MyUpdateResultset&#40;StringBuffer str&#41; throws Exception{
try{
MyUpdateResultset&#40;str.toString&#40;&#41;&#41;;
}catch&#40;Exception e&#41;{
}
}

public void MyUpdateResultset&#40;String str&#41; throws Exception{
try{
MyCloseResultset&#40;&#41;;
//g_stmSQL = g_connSQL.createStatement&#40;ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE&#41;;
g_stmSQL = g_connSQL.prepareStatement&#40;MyChinese2Unicode&#40;str.trim&#40;&#41;&#41;, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE&#41;;
g_stmSQL.executeUpdate&#40;&#41;;
MyCloseStatement&#40;&#41;;
}catch&#40;Exception e&#41;{
}
}

public String&#91;&#93; MyString2Array&#40;String src, String szsplit&#41; throws Exception{
String asz&#91;&#93; = null;
try{
java.util.StringTokenizer tokens = new java.util.StringTokenizer&#40;src,szsplit&#41;;
asz = new String&#91;tokens.countTokens&#40;&#41;&#93;;
for &#40;int i=0; tokens.hasMoreTokens&#40;&#41;; i++&#41; asz&#91;i&#93; = tokens.nextToken&#40;&#41;;
}catch&#40;Exception e&#41;{
}
return asz;
}

public void MyOpenResultset&#40;StringBuffer str&#41; throws Exception{
try{
MyOpenResultset&#40;str.toString&#40;&#41;, null&#41;;
}catch&#40;Exception e&#41;{
}
}

public void MyOpenResultset&#40;String str&#41; throws Exception{
try{
MyOpenResultset&#40;str, null&#41;;
}catch&#40;Exception e&#41;{
}
}

public void MyOpenResultset&#40;StringBuffer str, String param&#91;&#93;&#41; throws Exception{
try{
MyOpenResultset&#40;str.toString&#40;&#41;, param&#41;;
}catch&#40;Exception e&#41;{
}
}

public void MyOpenResultset&#40;String str, String param&#91;&#93;&#41; throws Exception{
try{
MyCloseResultset&#40;&#41;;
g_stmSQL = g_connSQL.prepareStatement&#40;MyChinese2Unicode&#40;str.trim&#40;&#41;&#41;, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE&#41;;
if &#40;param!=null&#41;{
   for &#40;int i=0; i&lt;param.length; i++&#41; g_stmSQL.setObject&#40;i+1, MyChinese2Unicode&#40;param&#91;i&#93;&#41;&#41;;
}
g_rstSQL=g_stmSQL.executeQuery&#40;&#41;;
}catch&#40;Exception e&#41;{
}
}

public void MyCloseConnection&#40;&#41; throws Exception{
try{
MyCloseResultset&#40;&#41;;
g_connSQL.close&#40;&#41;;
g_connSQL=null;
}catch&#40;Exception e&#41;{
}
}

public void MyCloseStatement&#40;&#41; throws Exception{
try{
g_stmSQL.close&#40;&#41;;
}catch&#40;Exception e&#41;{
}
g_stmSQL=null;
}

public void MyCloseResultset&#40;&#41; throws Exception{
try{
MyCloseStatement&#40;&#41;;
g_rstSQL.close&#40;&#41;;
}catch&#40;Exception e&#41;{
}
g_rstSQL=null;
}

public int MyString2int&#40;String str&#41; throws Exception{
try{
return Integer.parseInt&#40;str&#41;;
}catch&#40;Exception e&#41;{
return 0;
}
}

public String MyUnicode2Chinese&#40;String s&#41; throws Exception{
try{
if&#40;s==null||s.equals&#40;&quot;&quot;&#41;&#41; return &quot;&quot;;
String newstring=null;
newstring=new String&#40;s.getBytes&#40;&quot;ISO8859-1&quot;&#41;,&quot;gb2312&quot;&#41;;
return newstring;
}catch&#40;Exception e&#41;{
   return s;
}
}

public static String MyChinese2Unicode&#40;String s&#41; throws Exception{
try{
if&#40;s==null||s.equals&#40;&quot;&quot;&#41;&#41; return &quot;&quot;;
   String newstring=null;
   newstring=new String&#40;s.getBytes&#40;&quot;gb2312&quot;&#41;,&quot;ISO8859-1&quot;&#41;;
   return newstring;
}catch&#40;Exception e&#41;{
   return s;
}
}

%&gt;
页: [1]
查看完整版本: JSP连接数据库大全