我是菜鸟,刚刚开始学习jsp。现在遇到了困难,连接不上数据库。我用的是sql2000
解决方案 »
- struts2 页面重定向后找不到文件路径
- 乱码问题
- jasperreport 子报表数据源问题
- <% if ( sex!=null) %>else怎么写?
- 服务端如何调用OCX控件
- 怎样使用ResultSet对象可以得到一个结果集的记录数(就象在asp中RecordSet的RecordCount属性一样)?
- 求助:怎样取得上传图片的尺寸
- Jsp分页问题。。。
- 高手请教!,把一段JSP程序写成函数,然后,把那段JSP程序放在页面最下方,在页面中调用这个函数,这个函数怎么写啊??
- spring afterPropertiesSet执行修改sql无效
- com.fredck.FCKeditor.uploader.SimpleUploaderServletd
- 回答
比如:jsp代码???数据库的配置????以及每种表的制作等等。。
我说了我是个菜鸟,还不是很清楚,在这里先谢谢大家了!
我的qq是19444100,欢迎大家加我!(申请好友时注明“jsp”)
还有你说的url具体讲讲吧!
<%@ 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>
我身边就有很多的菜鸟刚学java又不好好看书的,都犯了这个低级的错误
<%Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
1 首先你要确保你的驱动jar包已经导入。
2 后面不知为何要加个newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
这个url貌似有问题,举个oracle的例子
url="jdbc:oracle:thin:@localhost:1521:orcl"
//pubs为你的数据库的
String user="sa";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
<%@ 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>
2、几个常用的重要技巧:
可滚动、更新的记录集
批量更新
事务处理 java数据库操作基本流程:取得数据库连接 - 执行sql语句 - 处理执行结果 - 释放数据库连接
1、取得数据库连接
1)用DriverManager取数据库连接
例子
String className,url,uid,pwd;
className = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:@127.0.0.1:1521:orasvr;
uid = "system";
pwd = "manager";
Class.forName(className);
Connection cn = DriverManager.getConnection(url,uid,pwd);
2)用jndi(java的命名和目录服务)方式
例子
String jndi = "jdbc/db";
Context ctx = (Context) new InitialContext().lookup("java:comp/env");
DataSource ds = (DataSource) ctx.lookup(jndi);
Connection cn = ds.getConnection();
多用于jsp中 2、执行sql语句
1)用Statement来执行sql语句
String sql;
Statement sm = cn.createStatement();
sm.executeQuery(sql); // 执行数据查询语句(select)
sm.executeUpdate(sql); // 执行数据更新语句(delete、update、insert、drop等)statement.close();
2)用PreparedStatement来执行sql语句
String sql;
sql = "insert into user (id,name) values (?,?)";
PreparedStatement ps = cn.prepareStatement(sql);
ps.setInt(1,xxx);
ps.setString(2,xxx);
...
ResultSet rs = ps.executeQuery(); // 查询
int c = ps.executeUpdate(); // 更新
3、处理执行结果
查询语句,返回记录集ResultSet
更新语句,返回数字,表示该更新影响的记录数
ResultSet的方法
1、next(),将游标往后移动一行,如果成功返回true;否则返回false
2、getInt("id")或getSting("name"),返回当前游标下某个字段的值
4、释放连接
cn.close();
一般,先关闭ResultSet,然后关闭Statement(或者PreparedStatement);最后关闭Connection
可滚动、更新的记录集
1、创建可滚动、更新的Statement
Statement sm = cn.createStatement(ResultSet.TYPE_SCROLL_ENSITIVE,ResultSet.CONCUR_READ_ONLY);
该Statement取得的ResultSet就是可滚动的
2、创建PreparedStatement时指定参数
PreparedStatemet ps = cn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); ResultSet.absolute(9000);
批量更新
1、Statement
Statement sm = cn.createStatement();
sm.addBatch(sql1);
sm.addBatch(sql2);
...
sm.executeBatch()
一个Statement对象,可以执行多个sql语句以后,批量更新。这多个语句可以是delete、update、insert等或兼有
2、PreparedStatement
PreparedStatement ps = cn.preparedStatement(sql);
{
ps.setXXX(1,xxx);
...
ps.addBatch();
}
ps.executeBatch();
一个PreparedStatement,可以把一个sql语句,变换参数多次执行,一次更新。
事务的处理
1、关闭Connection的自动提交
cn.setAutoCommit(false);
2、执行一系列sql语句
要点:执行每一个新的sql语句前,上一次执行sql语句的Statement(或者PreparedStatemet)必须先close
Statement sm ;
sm = cn.createStatement(insert into user...);
sm.executeUpdate();
sm.close(); sm = cn.createStatement("insert into corp...);
sm.executeUpdate();
sm.close(); 3、提交
cn.commit();
4、如果发生异常,那么回滚
cn.rollback();
String url="jdbc:oracle:thin:@localhost:1521:orcl"; //orcl为数据库的SID
String user="test";
String password="test";
Connection conn= DriverManager.getConnection(url,user,password); 2、DB2数据库 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); 3、Sql Server7.0/2000数据库 Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb";
//mydb为数据库
String user="sa";
String password="";
Connection conn= DriverManager.getConnection(url,user,password); 4、Sybase数据库 Class.forName("com.sybase.jdbc.SybDriver").newInstance();
String url =" jdbc:sybase:Tds:localhost:5007/myDB";//myDB为你的数据库名
Properties sysProps = System.getProperties();
SysProps.put("user","userid");
SysProps.put("password","user_password");
Connection conn= DriverManager.getConnection(url, SysProps); 4、Sybase数据库 Class.forName("com.informix.jdbc.IfxDriver").newInstance();
String url = "jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver;
user=testuser;password=testpassword"; //myDB为数据库名
Connection conn= DriverManager.getConnection(url); 6、MySQL数据库 Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1"
//myDB为数据库名
Connection conn= DriverManager.getConnection(url); 7、PostgreSQL数据库 Class.forName("org.postgresql.Driver").newInstance();
String url ="jdbc:postgresql://localhost/myDB" //myDB为数据库名
String user="myuser";
String password="mypassword";
Connection conn= DriverManager.getConnection(url,user,password); 8、access数据库直连用ODBC的Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ="+application.getRealPath("/Data/ReportDemo.mdb");
Connection conn = DriverManager.getConnection(url,"","");
Statement stmtNew=conn.createStatement() ; 二、JDBC连接MySql方式 下面是使用JDBC连接MySql的一个小的教程 1、查找驱动程序 MySQL目前提供的java驱动程序为Connection/J,可以从MySQL官方网站下载,并找到mysql-connector-java-3.0.15-ga-bin.jar文件,此驱动程序为纯java驱动程序,不需做其他配置。 2、动态指定classpath 如果需要执行时动态指定classpath,就在执行时采用-cp方式。否则将上面的.jar文件加入到classpath环境变量中。 3、加载驱动程序try{
Class.forName(com.mysql.jdbc.Driver);
System.out.println(Success loading Mysql Driver!);
}catch(Exception e)
{
System.out.println(Error loading Mysql Driver!);
e.printStackTrace();
} 4、设置连接的urljdbc:mysql://localhost/databasename[?pa=va][&pa=va]
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "DatabaseName=test;user=sa;password=123456";//此处用户名和密码为安装时自己设置的用户名和密码,根据自己的设置而定。//注意一个完整的字符串之间是以分号隔开不同的内容,但若以参数放入方法中,则以逗号隔开。
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
con = DriverManager.getConnection(connectionUrl);
String sql="select * from fruit";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%> <br>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
con.close(); %>
</body>
</html>
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
/**
* BaseDao类
* @author Administrator
*/
public class BaseDao {
public final static String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public final static String URL = "jdbc:sqlserver://localhost:1433;databasename=S2_BBS";
public final static String USER = "sa";
public final static String PASS = "ok";
private Connection con;
private Statement stm;
private PreparedStatement pstm;
private ResultSet rs; /*
* 打开数据库连接
*/
public void open() throws ClassNotFoundException, SQLException{
Class.forName(DRIVER);
this.con = DriverManager.getConnection(URL, USER, PASS);
}
/*
* 关闭数据库连接
*/
public void close() {
if(this.rs != null) {
try {
this.rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(this.pstm != null) {
try {
this.pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(this.stm != null) {
try {
this.stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(this.con != null) {
try {
this.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* Statement
* 增,删,改
*/
public int execSQL(String sql) throws SQLException {
this.stm = this.con.createStatement();
return this.stm.executeUpdate(sql);
}
/**
* Statement
* 查
*/
public ResultSet findSql(String sql) throws SQLException {
this.stm = this.con.createStatement();
this.rs = this.stm.executeQuery(sql);
return rs;
}
/**
* prepareStatement
* 增,删,改
*/
public int execSQL(String sql, List par) throws SQLException {
this.pstm = this.con.prepareStatement(sql);
if (null != par) {
for (int i = 0; i < par.size(); i++) {
this.pstm.setString(i + 1, par.get(i).toString());
}
}
return this.pstm.executeUpdate();
}
/**
* prepareStatement
* 查
*/
public ResultSet findSql(String sql, List par) throws SQLException {
this.pstm = this.con.prepareStatement(sql);
if (null != par) {
for (int i = 0; i < par.size(); i++) {
this.pstm.setString(i + 1, par.get(i).toString());
}
}
this.rs = this.pstm.executeQuery();
return this.rs;
}
}
它连接数据库一般有jdbc,odbc,当然你还可以用连接池(连接池可以配置在tomcat或struts……)
通常都用jdbc,而且一般都用mvc连接代码不会出现在jsp页面上
这是一个jdbc例子,他需要jar包package databaseu;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class DataBaseUtil {
//com.microsoft.sqlserver.jdbc.SQLServerDriver
private static final String jdbc_driver= "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String jdbc_url= "jdbc:sqlserver://localhost:1433;databaseName=sky";
public static Connection getcon(){
Connection conn = null;
try {
Class.forName(jdbc_driver);
conn= DriverManager.getConnection(jdbc_url,"sa","123");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void OtherClose(PreparedStatement pstmt,ResultSet rs){
try {
if (rs != null) {
rs.close();
rs = null;
}
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void ConnectionClose(Connection conn){ try {
if (conn != null || !conn.isClosed()) {
conn.close();
conn = null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这是Odbc不需要jar包但是需要配置数据源
Testdb { ResultSet rs=null;
public void (String args){
Testdb;
}
}
public Testdb{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:javadb";
conn=DriverManager.getConnection(url,"sa","");
stmt=conn.createStatement;
String sql="select * from tbuser";
rs=stmt.executeQuery(sql);
while(rs.next){
.out.prln(rs.getString("user_name")+rs.getString("user_password")+rs.getString("user_type"));
}
rs.close;
stmt.close;
conn.close;
}catch(Exception e){e.prStackTrace;}
}tomcat连接池配置:
把驱动添加到tomcat/lib中
D:\Program Files\Tomcat 6.0\conf\content.xml内添加了:
====================================================
<Resource
name="jdbc/sqlserverds" auth="Container"
type="javax.sql.DataSource"
password="sa"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
maxIdle="10"
maxWait="15000"
username="sa"
url="jdbc:sqlserver://localhost:1433;DatabaseName=XSCJ"
maxActive="1000" />工程中的WEB-INF中的web.xml中添加了:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/sqlserverds</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBDriver {
private final static String DRIVER="com.microsoft.jdbc.sqlserver.SQLServerDriver";
private final static String URL="jdbc:sqlserver://localhost:1433;databasename=...";
private final static String USER=" ";
private final static String PASSWORD=" ";
//加载驱动并测试连接
public static Connection getConnection(){
Connection conn=null;
try{
Class.forName(DRIVER);
conn=DriverManager.getConnection(URL,USER,PASSWORD);
if(conn!=null){
System.out.println("连接成功!");
}else{
System.out.println("连接失败!");
}
}
catch(Exception e){
e.printStackTrace();
}
return conn;
}
//关闭连接
private static void colseConn(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
}
2.再将三个文件驱动放到tomcat的lib下
3.然后写jsp连接数据库
4.电脑,tomcat,sqlserver2000 全部重启
5.测试通过
2.再将三个文件驱动放到tomcat的lib下
3.然后写jsp连接数据库
4.电脑,tomcat,sqlserver2000 全部重启
5.测试通过
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
Connection conn= DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=DBName","sa","");
//获取数据库连接