Java Blog From WeiChunHua

Java

常用链接

统计

develop

news

最新评论

2008年12月2日 #

JDBC连接数据库大全

          现在有好多初学jsp的网友经常会问数据库怎么连接啊,怎么老出错啊?所以我集中的在这写篇文章供大家参考,其实这种把数据库逻辑全部放在jsp里未必是好的做法,但是有利于初学者学习,所以我就这样做了,当大家学到一定程度的时候,可以考虑用MVC的模式开发。在练习这些代码的时候,你一定将jdbc的驱动程序放到服务器的类路径里,然后要在数据库里建一个表test,有两个字段比如为test1test2,可以用下面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","user_password");
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>

posted @ 2008-12-17 16:47 sunny spring 阅读(298) | 评论 (0)编辑 收藏

Hibernate入门程序

       以下程序是Hiberante入门程序:代码如下:首先说hibernate开发流程.A、准备一个POJO类  B、创建类的映射和配置文件(hibernate.cfg.xml  class.hbm.xml)class.hbm.xml此配置文件是必须与POJO类中的属性一一对应.
现在我以我创建的程序为例来进行说明:数据库为demo,表的名字为admin
1、POJO类

package com.wch.pojo;

public class Admin {
 private int id;
 private String username;
 private String password;
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
}

class.hbm.xml映射文件存放位置必须于POJO位置一致.也就是说必须放在同一个目录.hibernate.cfg.xml放在src根目录下.
2、创建hibernate.cfg.xml和class.hbm.xml(class指的是POJO类的名字)
class.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.wch.pojo.Admin" table="admin">
        <id name="id" type="integer">
            <column name="id" />
            <generator class="assigned"></generator>
        </id>
        <property name="username" type="string">
            <column name="username" length="32" not-null="false" />
        </property>
        <property name="password" type="string">
            <column name="password" length="20" not-null="false" />
        </property>
    </class>
</hibernate-mapping>
hibernate.cfg.xml:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
 <property name="dialect">
  org.hibernate.dialect.MySQLDialect
 </property>
 <property name="connection.url">
  jdbc:mysql://localhost:3306/demo
 </property>
 <property name="connection.username">root</property>
 <property name="connection.password">****</property>
 <property name="connection.driver_class">
  com.mysql.jdbc.Driver
 </property>
 <property name="myeclipse.connection.profile">mysql5.0</property>
 <property name="show_sql">true</property>
 <mapping resource="com/wch/pojo/Admin.hbm.xml" />

</session-factory>

</hibernate-configuration>


3、创建应用程序并进行代码测试:

package com.wch.op;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.wch.pojo.Admin;

public class UserOperation {
 public static void main(String[] args)throws Exception{
  Configuration config = new Configuration().configure();
  // 创建工厂
  SessionFactory factory = config.buildSessionFactory();
  // 打开session
  Session session = factory.openSession();
  // 事务提交
  try{
   Transaction tx = session.beginTransaction();
   // 创建对象
   Admin hb = new Admin();
   hb.setId(3);
   hb.setUsername("Hibernate3.2");
   hb.setPassword("20081202");
   //hb.setUsername("WCH");
   //hb.setPassword("Hibernate");
   // 执行插入语句,在hibernat中操作的是一个对象
   session.save(hb);
   // 提交事务
   tx.commit();
  }catch(Exception e)
  {
   System.out.println("error Msg:"+e.getMessage());
  }finally{
    // close session
    session.close();
  }
 }
}

更为详细的解释请参照Hibernate官方网站:www.hibernate.org


posted @ 2008-12-02 10:19 sunny spring 阅读(263) | 评论 (0)编辑 收藏