数据库JDBC驱动及URL介绍

来源:互联网 发布:牛客网算法视频百度云 编辑:程序博客网 时间:2024/05/24 01:07

一、装载并注册JDBC驱动程序,其中JDBC-ODBC Driver是在JDK中自带的,默认已经注册,所以不

需要再注册,
1.JDBC-ODBC 桥连
  装载JdbcOdbcDriver class
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
2.直连
 特别注意一个电脑同时装了SQL2000和SQL2005,那么其中一个端口要改,才能访问到,这里说一

下在我的电脑
 上右击选择管理-->找开服务和应用程序-->SQL Server配置管理器-->SQL Server2005网络配

置-->
 SQLEXPRESS的协议-->选择TCP/IP-->双击TCP/IP找开属性窗口-->选择IP地址选项-->把其中

所有TCP端口改为不同1433(即不冲突)就行了.然后要重启SQL2005的服务.
  装载并注册SQLServerDriver
  Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
  java.sql.DrjiverManager.registerDriver(new com.microsoft.jdbc.sqlserver.SQLServerdriver

());
  装载并注册OracleDriver
  Class.forName("oracle.jdbc.driver.Oracledriver");
  java.sql.DrjiverManager.registerDriver(new oracle.jdbc.driver.Oracledriver());
  装载并注册MySQLDriver
  Class.forName("com.mysql.jdbc.Driver");
  java.sql.DrjiverManager.registerDriver(new com.mysql.jdbc.Driver());
有些驱动程序类在被加载的时候,能自动创建本身的实例,然后调用

DrjiverManager.registerDriver()方法注册自身.
所以在实际中只要通过Class.forName方法加载即可,可以不必再注册驱动程序类.
二、建立与数据库的连接
   Connection con=DriverManager.getConnection(dburl,user,password);
   其中dburl表示连接数据库的JDBC URL,user和password分别表示连接数据库的用户名和口令

.
   JDBC URL的一般形式为:jdbc:drivertype:driversubtype://parameters
   其中drivertype表示驱动程序的类型,driversubtype是可选的参数,parameters通常用来设定数

据库服务器的IP地址、
   端口号和数据库的名称。几种常用的数据库的JDBC URL形式如下:
   1.JDBC-ODBC Driver(桥连)连接数据库:
   jdbc:odbc:datasource;其中datasource要在控制面板中的管理工具-->数据源(ODBC)中配置
   2.直连
   Oracle数据库连接:jdbc:oracle:thin:@localhost:1521:sid
   SQLServer数据库连接:jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=数据库名
   MySql数据库连接:jdbc:mysql://localhost:3306/数据库名
三、创建Statement对象:
    Statement st=con.createStatement();
四、创建PrepareStatement对象(针对有参数的SQL语句比如:select * from users where

name=? and password=?):
    PrepareStatement prepStmt=con.prepareStatement(sql语句);
    这个需要设置参数:
    prepStmt.setString(1,name)//1表示第一个参数,name表示name变量(一般是从外面传进来

的参数)
    prepStmt.setString(2,password)//1表示第一个参数,name表示password变量(一般是从外面

传进来的参数)
    注意PrepareStatement对象也可以执行不带参数的SQL语句.
五、调用SQL语句
    Statement可以用来执行对于insert、update、delete的SQL语句,调用语句是:

executeUpdate(SQL语句);
    对于select的SQL语句,调用语句是:executeQuery(SQL语句);
    PrepareStatement可以用来执行对于insert、update、delete的SQL语句,调用语句是:

executeUpdate();
    对于select的SQL语句,调用语句是:prepStmt.executeQuery();;
    while(rs.next()){               
       rs.getString(1)//其中1表示查询出来的集合中的第一列所对应的数据,
       //也可以用列名来表示1(如对应的列名为:name);  rs.getString("name");             
    }
六、CallableStatement对象可以执行存储过程,示例如下:
    protected CallableStatement cast=null;
    public List getBookByPage(int pageRow,int currentPage){
        int tatalPage=0;
        int tatalRow=0;
        this.getConn();
        List bookList=new ArrayList();
        try {
            cast = conn.prepareCall("{call proc_selectByPage(?,?,?,?)}");//前两个参数是输出参

数,要与存储过程相对应
            cast.registerOutParameter(1, Types.INTEGER);
            cast.registerOutParameter(2, Types.INTEGER);
            cast.setInt(3,pageRow);
            cast.setInt(4,currentPage);
            rs=cast.executeQuery();
            while(rs.next()){
                BookBean book=new BookBean();
                book.setBookID(rs.getString(1));
                book.setBookName(rs.getString(2));
                book.setBookdesc(rs.getString(3));
                book.setBookPrice(rs.getFloat(4));
                bookList.add(book);
            }
            tatalPage=cast.getInt(1);//得到存储过程的输出参数.
            tatalRow=cast.getInt(2);
            bookList.add(tatalPage+"");
            bookList.add(tatalRow+"");
        } catch (SQLException ex) {
            ex.printStackTrace();
        }finally{
            this.closeAll();
        }
        return bookList;
    }
   

 

七:SQL数据库脚本示例如下"

use master
go
exec xp_cmdshell 'mkdir d:/project'
go
if exists(select * from sysdatabases where name ='commodityDB')
 drop database commodityDB
go
create database commodityDB
on primary
(
name='commodity_data',
filename='d:/project/commodity_data.mdf',
size=1mb,
filegrowth=20%
)
log on
(
name='commodity_log',
filename='d:/project/commodity_log.ldf',
size=1mb,
filegrowth=20%
)
go
use commodityDB
go
if exists(select * from sysobjects where name='commodity')
 drop table commodity
go
create table commodity
(
comID  int  identity(1,1) primary key,
comName  varchar(50) not null unique(comName),
comDesc  varchar(50) not null,
comPrice numeric(10,2) not null,
comUnit  varchar(10) not null default('pcs')
)
select * from commodity

--插入数据
insert into commodity(comName,comDesc,comPrice,comUnit) values('JAVA程序设计','人民出版社',20.6,'本') 
insert into commodity(comName,comDesc,comPrice,comUnit) values('.NET程序设计','四川大学出版社',60.7,'本')

--创建分页的存过程
use commodityDB
go
if exists(select * from sysobjects where name='proc_selectByPage')
 drop proc proc_selectByPage
go
create proc proc_selectByPage
 @tatalPage int output,
 @tatalRow int output,
 @pageRow int,
 @currentPage int
as
 declare @startRow int,@endRow int
 declare @tempTable table(TID int identity(1,1),comID int)
 select @tatalRow=count(*) from commodity
 set @tatalPage=@tatalRow/@pageRow
 if(@tatalRow/@pageRow<>0)
 begin
  set @tatalPage=@tatalPage+1
 end
 if(@currentPage>@tatalPage)
 begin
  set @currentPage=@tatalPage
 end
 if(@currentPage<1)
 begin
  set @currentPage=1
 end
 set @startRow=(@currentPage-1)*@pageRow+1
 set @endRow=@currentPage*@pageRow
 insert into @tempTable(comID) select comID from commodity order by comID
 select com.comID,comName,comDesc,comPrice,comUnit
               from commodity com,@tempTable tt where com.comID=tt.comID and tt.comID>=@startRow and tt.comID<=@endRow
go
--测试存储过程
select * from commodity
set nocount on
declare @tatalPage int ,@tatalRow int
exec proc_selectByPage @tatalpage output,@tatalRow output,5,8
print '总页数:'+convert(varchar(10),@tatalPage)
print '总记录数:'+convert(varchar(10),@tatalRow)

 

八:

SQL Server 2005 中引入的 xp_cmdshell 选项是服务器配置选项,使系统管理员能够控制是否可以在系统上执行 xp_cmdshell 扩展存储过程。默认情况下,xp_cmdshell 选项在新安装的软件上处于禁用状态,但是可以通过使用外围应用配置器工具或运行 sp_configure 系统存储过程来启用它,如下面的代码示例所示:
解决方法:允许下面的语句
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO

执行完之后就不会再报SQL Server 阻止了对组件 'xp_cmdshell' 的 过程'sys.xp_cmdshell' 的访问的错误了


--以下四句解决 阻止了对组件 'xp_cmdshell' 的 过程
exec sp_configure 'show advanced options', 1
RECONFIGURE
exec sp_configure 'xp_cmdshell', 1
RECONFIGURE