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>
<%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()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
二、jsp连接Sql Server7.0/2000数据库
testsqlserver.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%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()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
三、jsp连接DB2数据库
testdb2.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%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()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
四、jsp连接Informix数据库
testinformix.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%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()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
五、jsp连接Sybase数据库
testmysql.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%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()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
六、jsp连接MySQL数据库
testmysql.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost/softforum?user=soft&password=soft1234&useUnicode=true&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()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
七、jsp连接PostgreSQL数据库
testmysql.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%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()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html> 题外话:ASP的?!
题外话:ASP的?!
现在很多搞asp的都在转学jsp,所以........ :-)
不过我帮你找找 嗬嗬,我加一个连接可以access(中文查询)的:P
例:
g_drvSQL = (Driver)Class.forName(MM_testjdbc_DRIVER).newInstance();;
g_connSQL = DriverManager.getConnection(MM_testjdbc_STRING,MM_testjdbc_USERNAME,MM_testjdbc_PASSWORD);
String aszParam[] = {"游客"};
MyOpenResultset("SELECT *FROM 注册用户列表 WHERE realname LIKE ?",aszParam);
返回的ResultSet为:
g_rstSQL
<%!
// resultset
Driver g_drvSQL = null;
Connection g_connSQL = null;
PreparedStatement g_stmSQL = null;
ResultSet g_rstSQL = null;
public String MyGetColumn(String str) throws Exception{
Object objData;
objData = (((objData = g_rstSQL.getObject(str))==null || g_rstSQL.wasNull())?"":objData);
return MyUnicode2Chinese(objData.toString());
}
public String[] MyFormatsql(ServletRequest request, String columns, String fields, int ntype) throws Exception{
String aszReturn[] = {"",""};
String[] MM_fields = null, MM_columns = null;
try{
//get from form first
java.util.StringTokenizer tokens = new java.util.StringTokenizer(fields,"|");
MM_fields = new String[tokens.countTokens()];
for (int i=0; tokens.hasMoreTokens(); i++) MM_fields[i] = tokens.nextToken();
tokens = new java.util.StringTokenizer(columns,"|");
MM_columns = new String[tokens.countTokens()];
for (int i=0; tokens.hasMoreTokens(); i++) MM_columns[i] = tokens.nextToken();
// set the form values
for (int i=0; i+1 < MM_fields.length; i+=2) {
MM_fields[i+1] = ((request.getParameter(MM_fields[i])!=null)?(String)request.getParameter(MM_fields[i]):"");
}
if (0==ntype){
StringBuffer buffer = new StringBuffer();
//update
// create the update sql statement
//MM_editQuery = new StringBuffer("update ").append(MM_editTable).append(" set ");
for (int i=0; i+1 < MM_fields.length; i+=2) {
String formVal = MM_fields[i+1];
String elem;
tokens = new java.util.StringTokenizer(MM_columns[i+1],",");
String delim = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
String altVal = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
String emptyVal = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
if (formVal.length() == 0) {
formVal = emptyVal;
} else {
if (altVal.length() != 0) {
formVal = altVal;
} else if (delim.compareTo("'") == 0) {// escape quotes
StringBuffer escQuotes = new StringBuffer(formVal);
for (int j=0; j < escQuotes.length(); j++)
if (escQuotes.charAt(j) == '\'') escQuotes.insert(j++,'\'');
formVal = "'" + escQuotes + "'";
} else {
formVal = delim + formVal + delim;
}
}
buffer.append((i!=0)?",":"").append(MM_columns[i]).append(" = ").append(formVal);
}
aszReturn[0] = buffer.toString();
}else if(1==ntype){
//insert
StringBuffer MM_tableValues = new StringBuffer(), MM_dbValues = new StringBuffer();
for (int i=0; i+1 < MM_fields.length; i+=2) {
String formVal = MM_fields[i+1];
String elem;
tokens = new java.util.StringTokenizer(MM_columns[i+1],",");
String delim = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
String altVal = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
String emptyVal = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
if (formVal.length() == 0) {
formVal = emptyVal;
} else {
if (altVal.length() != 0) {
formVal = altVal;
} else if (delim.compareTo("'") == 0) {// escape quotes
StringBuffer escQuotes = new StringBuffer(formVal);
for (int j=0; j < escQuotes.length(); j++)
if (escQuotes.charAt(j) == '\'') escQuotes.insert(j++,'\'');
formVal = "'" + escQuotes + "'";
} else {
formVal = delim + formVal + delim;
}
}
MM_tableValues.append((i!=0)?",":"").append(MM_columns[i]);
MM_dbValues.append((i!=0)?",":"").append(formVal);
}
aszReturn[0] = MM_tableValues.toString();
aszReturn[1] = MM_dbValues.toString();
}
return aszReturn;
}catch(Exception e){
return null;
}
}
public void MyUpdateResultset(StringBuffer str) throws Exception{
try{
MyUpdateResultset(str.toString());
}catch(Exception e){
}
}
public void MyUpdateResultset(String str) throws Exception{
try{
MyCloseResultset();
//g_stmSQL = g_connSQL.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
g_stmSQL = g_connSQL.prepareStatement(MyChinese2Unicode(str.trim()), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
g_stmSQL.executeUpdate();
MyCloseStatement();
}catch(Exception e){
}
}
public String[] MyString2Array(String src, String szsplit) throws Exception{
String asz[] = null;
try{
java.util.StringTokenizer tokens = new java.util.StringTokenizer(src,szsplit);
asz = new String[tokens.countTokens()];
for (int i=0; tokens.hasMoreTokens(); i++) asz[i] = tokens.nextToken();
}catch(Exception e){
}
return asz;
}
public void MyOpenResultset(StringBuffer str) throws Exception{
try{
MyOpenResultset(str.toString(), null);
}catch(Exception e){
}
}
public void MyOpenResultset(String str) throws Exception{
try{
MyOpenResultset(str, null);
}catch(Exception e){
}
}
public void MyOpenResultset(StringBuffer str, String param[]) throws Exception{
try{
MyOpenResultset(str.toString(), param);
}catch(Exception e){
}
}
public void MyOpenResultset(String str, String param[]) throws Exception{
try{
MyCloseResultset();
g_stmSQL = g_connSQL.prepareStatement(MyChinese2Unicode(str.trim()), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
if (param!=null){
for (int i=0; i<param.length; i++) g_stmSQL.setObject(i+1, MyChinese2Unicode(param[i]));
}
g_rstSQL=g_stmSQL.executeQuery();
}catch(Exception e){
}
}
public void MyCloseConnection() throws Exception{
try{
MyCloseResultset();
g_connSQL.close();
g_connSQL=null;
}catch(Exception e){
}
}
public void MyCloseStatement() throws Exception{
try{
g_stmSQL.close();
}catch(Exception e){
}
g_stmSQL=null;
}
public void MyCloseResultset() throws Exception{
try{
MyCloseStatement();
g_rstSQL.close();
}catch(Exception e){
}
g_rstSQL=null;
}
public int MyString2int(String str) throws Exception{
try{
return Integer.parseInt(str);
}catch(Exception e){
return 0;
}
}
public String MyUnicode2Chinese(String s) throws Exception{
try{
if(s==null||s.equals("")) return "";
String newstring=null;
newstring=new String(s.getBytes("ISO8859-1"),"gb2312");
return newstring;
}catch(Exception e){
return s;
}
}
public static String MyChinese2Unicode(String s) throws Exception{
try{
if(s==null||s.equals("")) return "";
String newstring=null;
newstring=new String(s.getBytes("gb2312"),"ISO8859-1");
return newstring;
}catch(Exception e){
return s;
}
}
%>
页:
[1]