﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-Sealyu-随笔分类-数据库</title><link>http://www.blogjava.net/sealyu/category/30677.html</link><description>--- The devil's in the Details (&lt;a href="http://www.sealyu.com"&gt;http://www.sealyu.com&lt;/a&gt;)</description><language>zh-cn</language><lastBuildDate>Mon, 29 Nov 2010 21:02:46 GMT</lastBuildDate><pubDate>Mon, 29 Nov 2010 21:02:46 GMT</pubDate><ttl>60</ttl><item><title>Hibernate, UTF-8 and SQL Server 2005 </title><link>http://www.blogjava.net/sealyu/archive/2010/11/29/339341.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Mon, 29 Nov 2010 10:49:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2010/11/29/339341.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/339341.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2010/11/29/339341.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/339341.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/339341.html</trackback:ping><description><![CDATA[<p>I found out today that MS Sql server seems to handle Unicode in a
very special way. Instead of having some support a database or table
level, each Unicode column have to be created as &#8220;national&#8221;. That is be
either nchar, nvarchar or ntext.</p>
<p>Ms SQL Server 2005 seems to go one step further by announcing future deprecation for <em>ntext</em>, <em>text</em> and <em>image</em> types.</p>
<p>From Sql Server 2005 <a href="http://msdn2.microsoft.com/en-us/library/ms187993.aspx">notes</a>:</p>
<p>&#8220;<strong>ntext</strong>, <strong>text</strong>, and <strong>image</strong>
data types will be removed in a future version of Microsoft SQL Server.
Avoid using these data types in new development work, and plan to
modify applications that currently use them. Use <a href="http://msdn2.microsoft.com/en-us/library/ms186939.aspx" onclick="javascript:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl05',this);">nvarchar(max)</a>, <a href="http://msdn2.microsoft.com/en-us/library/ms176089.aspx" onclick="javascript:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl06',this);">varchar(max)</a>, and <a href="http://msdn2.microsoft.com/en-us/library/ms188362.aspx" onclick="javascript:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl07',this);">varbinary(max)</a> instead.&#8221;</p>
<p>When working with Hibernate it seems there is no dialect to handle
Unicode integration properly. You have to get down and write a custom
dialect that maps to the new data types.</p>
<pre>/**<br />
* Unicode support in SQL Server<br />
*<br />
* @author icocan<br />
*/<br />
public class UnicodeSQLServerDialect extends SQLServerDialect {<br />
<br />
public UnicodeSQLServerDialect() {<br />
super();<br />
<br />
// Use Unicode Characters<br />
registerColumnType(Types.VARCHAR, 255, "nvarchar($l)");<br />
registerColumnType(Types.CHAR, "nchar(1)");<br />
registerColumnType(Types.CLOB, "nvarchar(max)");<br />
<br />
// Microsoft SQL Server 2000 supports bigint and bit<br />
registerColumnType(Types.BIGINT, "bigint");<br />
registerColumnType(Types.BIT, "bit");<br />
}<br />
}</pre>
<div style="float: right;">
<a href="http://blog.tremend.ro/2007/05/23/hibernate-utf-8-and-sql-server-2005/" rel="bookmark" title="Permanent Link to Hibernate, UTF-8 and SQL Server 2005">
read more ...</a>
</div>
<br />
You have to write your own SQLServerDialect class, it looks something like this:
<pre><code>publicclassSQLServerNativeDialectextendsSQLServerDialect{<br />
&nbsp; &nbsp; &nbsp;publicSQLServerNativeDialect(){<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;super();<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;registerColumnType(Types.VARCHAR,"nvarchar($l)");<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;registerColumnType(Types.CLOB,"nvarchar(max)");<br />
&nbsp; &nbsp; &nbsp;}<br />
<br />
&nbsp; &nbsp; publicString getTypeName(int code,int length,int precision,int scale)throwsHibernateException{<br />
&nbsp; &nbsp; &nbsp; &nbsp; if(code !=2005){<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; returnsuper.getTypeName(code, length, precision, scale);<br />
&nbsp; &nbsp; &nbsp; &nbsp; }else{<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return"ntext";<br />
&nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; }<br />
}<br />
</code></pre>
<p>This class maps Hibernate's types to SQL types, so the class will map the  <strong><em>nvarchar(max)</em></strong> SQL Data Type to Hibernate's <strong><em>CLOB</em></strong> data type.</p>
<p>The <strong><em>getTypeName</em></strong> method is used to return
"ntext" when Hibernate asks about the data type with code 2005 (which
looks like it's the nvarchar(max) data type).</p>
<p>Finally, you need to change your hibernate persistence dialect to
this new SQLServerDialect class, which allows hibernate to translate
data types into SQL data types.</p>
<br />
<img src ="http://www.blogjava.net/sealyu/aggbug/339341.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2010-11-29 18:49 <a href="http://www.blogjava.net/sealyu/archive/2010/11/29/339341.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>nvarchar与varchar的区别</title><link>http://www.blogjava.net/sealyu/archive/2010/11/29/339293.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Mon, 29 Nov 2010 02:51:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2010/11/29/339293.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/339293.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2010/11/29/339293.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/339293.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/339293.html</trackback:ping><description><![CDATA[<p>nvarchar与varchar的区别</p>
<p>varchar[(n)] &nbsp; <br />
&nbsp; 长度为 &nbsp; n &nbsp; 个字节的可变长度且非 &nbsp; Unicode &nbsp; 的字符数据。n &nbsp;
必须是一个介于 &nbsp; 1 &nbsp; 和 &nbsp; 8,000 &nbsp; 之间的数值。存储大小为输入数据的字节的实际长度，而不是 &nbsp; n &nbsp;
个字节。所输入的数据字符长度可以为零。varchar &nbsp; 在 &nbsp; SQL-92 &nbsp; 中的同义词为 &nbsp; char &nbsp; varying &nbsp; 或 &nbsp;
character &nbsp; varying。 &nbsp; <br />
&nbsp; &nbsp; <br />
&nbsp; nvarchar(n) &nbsp; <br />
&nbsp; 包含 &nbsp; n &nbsp;
个字符的可变长度 &nbsp; Unicode &nbsp; 字符数据。n &nbsp; 的值必须介于 &nbsp; 1 &nbsp; 与 &nbsp; 4,000 &nbsp;
之间。字节的存储大小是所输入字符个数的两倍。所输入的数据字符长度可以为零。nvarchar &nbsp; 在 &nbsp; SQL-92 &nbsp; 中的同义词为 &nbsp;
national &nbsp; char &nbsp; varying &nbsp; 和 &nbsp; national &nbsp; character &nbsp; varying。&nbsp;&nbsp; </p>
<p>通俗一點就是varchar適合輸入英文和數字，nvarchar一般用做中文或其它語言的輸入，這樣到別的語系不會出現亂碼:))</p>
<img src ="http://www.blogjava.net/sealyu/aggbug/339293.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2010-11-29 10:51 <a href="http://www.blogjava.net/sealyu/archive/2010/11/29/339293.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>sql server 判断表/视图/存储过程是否存在（转）</title><link>http://www.blogjava.net/sealyu/archive/2010/05/28/322100.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Thu, 27 May 2010 18:40:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2010/05/28/322100.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/322100.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2010/05/28/322100.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/322100.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/322100.html</trackback:ping><description><![CDATA[--如果是实表可以用<br />
if exists (select * from sysobjects where id = object_id(N'[dbo].[表名]')
and OBJECTPROPERTY(id, N'IsUserTable') = 1) <br />
drop table [dbo].[表名]
<p>--如果是临时表可以用(说明,如果用查找实表方法来打临时表会找不到.发布区别对代.)<br />
if object_id('tempdb..##temp') is not null<br />
&nbsp;&nbsp;  drop table ##temp</p>
<p>--判断存储过程是否存在<br />
if exists(select 1 from sysobjects where id=object_id('所有者.存储过程名') and
xtype='P')&nbsp;&nbsp;  <br />
print '存在'&nbsp;&nbsp;  <br />
else&nbsp;&nbsp;  <br />
print '不存在'</p>
<p>--判断视图是否存在<br />
--SQL Server 2000 <br />
IF EXISTS (SELECT * FROM sysviews WHERE object_id = '[dbo].[视图名]' <br />
--SQL Server 2005 <br />
IF EXISTS (SELECT * FROM sys.views WHERE object_id = '[dbo].[视图名]'</p>
<p><br />
/*<br />
sysObjects ( <br />
Name sysname,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  --object 名称 <br />
id&nbsp;&nbsp;  int,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  --object id <br />
xtype char(2),&nbsp;&nbsp;&nbsp;&nbsp;  -- object 类型&nbsp;&nbsp;  <br />
type  char(2),&nbsp;&nbsp;&nbsp;&nbsp;  -- Object 类型（与xtype 似乎一模一样？ 有点郁闷&#8230;）  <br />
uid&nbsp;&nbsp;  smallint,&nbsp;&nbsp;&nbsp;&nbsp;  -- object 所有者的ID <br />
...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  --其他的字段不常用到。&nbsp;&nbsp;  <br />
)</p>
<p>sysobjects的xtype 代表的对象类型。可以是下列对象类型中的一种： <br />
C = CHECK 约束 <br />
D = 默认值或 DEFAULT 约束 <br />
F = FOREIGN KEY 约束 <br />
L = 日志 <br />
FN = 标量函数 <br />
IF = 内嵌表函数 <br />
P = 存储过程 <br />
PK = PRIMARY KEY 约束（类型是 K） <br />
RF = 复制筛选存储过程 <br />
S = 系统表 <br />
TF = 表函数 <br />
TR = 触发器 <br />
U = 用户表 <br />
UQ = UNIQUE 约束（类型是 K） <br />
V = 视图 <br />
X = 扩展存储过程 </p>
<p><br />
object_id和data_object_id都是表示数据库对象的唯一标志。<br />
<br />
object_id是数据库对象的逻辑id，data_object_id是数据库对象的物理id。<br />
<br />
如果一些object没有物理属性的话那它就不存在data_object_id，例如procedure,function,package,data
type,db
link,mv定义，view定义，临时表，分区表定义等等这些object都是没有对应着某个segment，因此它们的data_object_id
都为空。<br />
<br />
当一个表建立的时候，他的object_id 和
data_object_id是相等的。当表move和truncate后data_object_id会发生变化。修改表结构不会更改。<br />
<br />
select object_id,data_object_id from user_objects where object_name=&#8217;T';<br />
OBJECT_ID DATA_OBJECT_ID<br />
———- ————&#8211;<br />
63053 63464<br />
<br />
SELECT HEADER_FILE,HEADER_BLOCK,BLOCKS FROM DBA_SEGMENTS WHERE
SEGMENT_NAME=&#8217;T&#8217; AND OWNER=&#8217;TEST&#8217;;<br />
HEADER_FILE HEADER_BLOCK BLOCKS<br />
———&#8211; ———— ———-<br />
4 467 8</p>
<p>*/</p>
<p><br />
SELECT * FROM sysobjects WHERE xtype='U' AND id=OBJECT_ID('Booking')</p>
<img src ="http://www.blogjava.net/sealyu/aggbug/322100.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2010-05-28 02:40 <a href="http://www.blogjava.net/sealyu/archive/2010/05/28/322100.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>MySQLdb User's Guide</title><link>http://www.blogjava.net/sealyu/archive/2010/05/17/321217.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Mon, 17 May 2010 15:56:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2010/05/17/321217.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/321217.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2010/05/17/321217.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/321217.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/321217.html</trackback:ping><description><![CDATA[<div topic="">
<p first=""><a id="contents" name="contents">Contents</a></p>
<ul>
    <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#introduction" id="id1" name="id1">Introduction</a></li>
    <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#installation" id="id2" name="id2">Installation</a></li>
    <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#mysql" id="id3" name="id3">_mysql</a>
    <ul>
        <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#mysql-c-api-translation" id="id4" name="id4">MySQL C API translation</a></li>
        <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#mysql-c-api-function-mapping" id="id5" name="id5">MySQL C API function mapping</a></li>
        <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#some-mysql-examples" id="id6" name="id6">Some _mysql examples</a></li>
    </ul>
    </li>
    <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#mysqldb" id="id7" name="id7">MySQLdb</a>
    <ul>
        <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#functions-and-attributes" id="id8" name="id8">Functions and attributes</a></li>
        <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#connection-objects" id="id9" name="id9">Connection Objects</a></li>
        <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#cursor-objects" id="id10" name="id10">Cursor Objects</a></li>
        <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#some-examples" id="id11" name="id11">Some examples</a></li>
    </ul>
    </li>
    <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#using-and-extending" id="id12" name="id12">Using and extending</a></li>
    <li><a href="http://mysql-python.sourceforge.net/MySQLdb.html#embedded-server" id="id13" name="id13">Embedded Server</a></li>
</ul>
</div>
<div>
<h1><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id1" id="introduction" name="introduction">Introduction</a></h1>
<p>MySQLdb is an thread-compatible interface to the popular MySQL
database server that provides the Python database API.</p>
</div>
<div>
<h1><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id2" id="installation" name="installation">Installation</a></h1>
<p>The <tt literal="">README</tt>
file has complete installation instructions.</p>
</div>
<div>
<h1><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id3" id="mysql" name="mysql">_mysql</a></h1>
<p>If you want to write applications which are portable across
databases,
use <a href="http://mysql-python.sourceforge.net/MySQLdb.html#mysqldb">MySQLdb</a>,
and avoid using this module directly. <tt literal="">_mysql</tt>
provides an interface which mostly implements the MySQL C API. For
more information, see the <a href="http://dev.mysql.com/doc/">MySQL documentation</a>. The
documentation
for this module is intentionally weak because you probably should use
the higher-level MySQLdb module. If you really need it, use the
standard MySQL docs and transliterate as necessary.</p>
<div>
<h2><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id4" id="mysql-c-api-translation" name="mysql-c-api-translation">MySQL C API
translation</a></h2>
<p>The MySQL C API has been wrapped in an object-oriented way. The only
MySQL data structures which are implemented are the <tt literal="">MYSQL</tt>
(database connection handle) and <tt literal="">MYSQL_RES</tt> (result handle)
types. In general, any function which takes <tt literal="">MYSQL *mysql</tt> as an
argument is now a method of the connection object, and any function
which takes <tt literal="">MYSQL_RES
*result</tt> as an argument is a method of the
result object. Functions requiring none of the MySQL data structures
are implemented as functions in the module. Functions requiring one of
the other MySQL data structures are generally not implemented.
Deprecated functions are not implemented. In all cases, the <tt literal="">mysql_</tt>
prefix is dropped from the name. Most of the <tt literal="">conn</tt> methods listed
are also available as MySQLdb Connection object methods. Their use is
non-portable.</p>
</div>
<div>
<h2><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id5" id="mysql-c-api-function-mapping" name="mysql-c-api-function-mapping">MySQL
C API function mapping</a></h2>
<table border="1">
    <colgroup>
    <col width="47%">
    <col width="53%">
    </colgroup>
    <thead valign="bottom">
        <tr>
            <th>C API</th>
            <th><tt literal="">_mysql</tt></th>
        </tr>
    </thead>
    <tbody valign="top">
        <tr>
            <td><tt literal="">mysql_affected_rows()</tt></td>
            <td><tt literal="">conn.affected_rows()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_autocommit()</tt></td>
            <td><tt literal="">conn.autocommit()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_character_set_name()</tt></td>
            <td><tt literal="">conn.character_set_name()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_close()</tt></td>
            <td><tt literal="">conn.close()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_commit()</tt></td>
            <td><tt literal="">conn.commit()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_connect()</tt></td>
            <td><tt literal="">_mysql.connect()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_data_seek()</tt></td>
            <td><tt literal="">result.data_seek()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_debug()</tt></td>
            <td><tt literal="">_mysql.debug()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_dump_debug_info</tt></td>
            <td><tt literal="">conn.dump_debug_info()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_escape_string()</tt></td>
            <td><tt literal="">_mysql.escape_string()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_fetch_row()</tt></td>
            <td><tt literal="">result.fetch_row()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_get_character_set_info()</tt></td>
            <td><tt literal="">conn.get_character_set_info()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_get_client_info()</tt></td>
            <td><tt literal="">_mysql.get_client_info()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_get_host_info()</tt></td>
            <td><tt literal="">conn.get_host_info()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_get_proto_info()</tt></td>
            <td><tt literal="">conn.get_proto_info()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_get_server_info()</tt></td>
            <td><tt literal="">conn.get_server_info()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_info()</tt></td>
            <td><tt literal="">conn.info()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_insert_id()</tt></td>
            <td><tt literal="">conn.insert_id()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_num_fields()</tt></td>
            <td><tt literal="">result.num_fields()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_num_rows()</tt></td>
            <td><tt literal="">result.num_rows()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_options()</tt></td>
            <td>various options to <tt literal="">_mysql.connect()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_ping()</tt></td>
            <td><tt literal="">conn.ping()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_query()</tt></td>
            <td><tt literal="">conn.query()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_real_connect()</tt></td>
            <td><tt literal="">_mysql.connect()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_real_query()</tt></td>
            <td><tt literal="">conn.query()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_real_escape_string()</tt></td>
            <td><tt literal="">conn.escape_string()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_rollback()</tt></td>
            <td><tt literal="">conn.rollback()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_row_seek()</tt></td>
            <td><tt literal="">result.row_seek()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_row_tell()</tt></td>
            <td><tt literal="">result.row_tell()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_select_db()</tt></td>
            <td><tt literal="">conn.select_db()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_set_character_set()</tt></td>
            <td><tt literal="">conn.set_character_set()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_ssl_set()</tt></td>
            <td><tt literal="">ssl</tt>
            option to <tt literal="">_mysql.connect()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_stat()</tt></td>
            <td><tt literal="">conn.stat()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_store_result()</tt></td>
            <td><tt literal="">conn.store_result()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_thread_id()</tt></td>
            <td><tt literal="">conn.thread_id()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_thread_safe_client()</tt></td>
            <td><tt literal="">conn.thread_safe_client()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_use_result()</tt></td>
            <td><tt literal="">conn.use_result()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">mysql_warning_count()</tt></td>
            <td><tt literal="">conn.warning_count()</tt></td>
        </tr>
        <tr>
            <td><tt literal="">CLIENT_*</tt></td>
            <td><tt literal="">MySQLdb.constants.CLIENT.*</tt></td>
        </tr>
        <tr>
            <td><tt literal="">CR_*</tt></td>
            <td><tt literal="">MySQLdb.constants.CR.*</tt></td>
        </tr>
        <tr>
            <td><tt literal="">ER_*</tt></td>
            <td><tt literal="">MySQLdb.constants.ER.*</tt></td>
        </tr>
        <tr>
            <td><tt literal="">FIELD_TYPE_*</tt></td>
            <td><tt literal="">MySQLdb.constants.FIELD_TYPE.*</tt></td>
        </tr>
        <tr>
            <td><tt literal="">FLAG_*</tt></td>
            <td><tt literal="">MySQLdb.constants.FLAG.*</tt></td>
        </tr>
    </tbody>
</table>
</div>
<div>
<h2><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id6" id="some-mysql-examples" name="some-mysql-examples">Some _mysql examples</a></h2>
<p>Okay, so you want to use <tt literal="">_mysql</tt> anyway. Here are some examples.</p>
<p>The simplest possible database connection is:</p>
<pre>import _mysql<br />
db=_mysql.connect()<br />
</pre>
<p>This creates a connection to the MySQL server running on the local
machine using the standard UNIX socket (or named pipe on Windows),
your login name (from the USER environment variable), no password, and
does not <tt literal="">USE</tt> a
database.  Chances are you need to supply more
information.:</p>
<pre>db=_mysql.connect("localhost","joebob","moonpie","thangs")<br />
</pre>
<p>This creates a connection to the MySQL server running on the local
machine via a UNIX socket (or named pipe), the user name "joebob", the
password "moonpie", and selects the initial database "thangs".</p>
<p>We haven't even begun to touch upon all the parameters <tt literal="">connect()</tt>
can take.  For this reason, I prefer to use keyword parameters:</p>
<pre>db=_mysql.connect(host="localhost",user="joebob",<br />
passwd="moonpie",db="thangs")<br />
</pre>
<p>This does exactly what the last example did, but is arguably easier
to
read. But since the default host is "localhost", and if your login
name really was "joebob", you could shorten it to this:</p>
<pre>db=_mysql.connect(passwd="moonpie",db="thangs")<br />
</pre>
<p>UNIX sockets and named pipes don't work over a network, so if you
specify a host other than localhost, TCP will be used, and you can
specify an odd port if you need to (the default port is 3306):</p>
<pre>db=_mysql.connect(host="outhouse",port=3307,passwd="moonpie",db="thangs")<br />
</pre>
<p>If you really had to, you could connect to the local host with TCP by
specifying the full host name, or 127.0.0.1.</p>
<p>Generally speaking, putting passwords in your code is not such a good
idea:</p>
<pre>db=_mysql.connect(host="outhouse",db="thangs",read_default_file="~/.my.cnf")<br />
</pre>
<p>This does what the previous example does, but gets the username and
password and other parameters from ~/.my.cnf (UNIX-like systems). Read
about <a href="http://dev.mysql.com/doc/mysql/en/Option_files.html">option files</a>
for more details.</p>
<p>So now you have an open connection as <tt literal="">db</tt> and want to do a
query. Well, there are no cursors in MySQL, and no parameter
substitution, so you have to pass a complete query string to
<tt literal="">db.query()</tt>:</p>
<pre>db.query("""SELECT spam, eggs, sausage FROM breakfast<br />
WHERE price &lt; 5""")<br />
</pre>
<p>There's no return value from this, but exceptions can be raised. The
exceptions are defined in a separate module, <tt literal="">_mysql_exceptions</tt>,
but <tt literal="">_mysql</tt>
exports them. Read DB API specification <a href="http://www.python.org/peps/pep-0249.html">PEP-249</a> to
find out what they are, or you can use the catch-all <tt literal="">MySQLError</tt>.</p>
<p>At this point your query has been executed and you need to get the
results. You have two options:</p>
<pre>r=db.store_result()<br />
# ...or...<br />
r=db.use_result()<br />
</pre>
<p>Both methods return a result object. What's the difference?
<tt literal="">store_result()</tt>
returns the entire result set to the client
immediately. If your result set is really large, this could be a
problem. One way around this is to add a <tt literal="">LIMIT</tt> clause to your
query, to limit the number of rows returned. The other is to use
<tt literal="">use_result()</tt>,
which keeps the result set in the server and sends
it row-by-row when you fetch. This does, however, tie up server
resources, and it ties up the connection: You cannot do any more
queries until you have fetched <strong>all</strong> the rows. Generally I
recommend using <tt literal="">store_result()</tt>
unless your result set is really
huge and you can't use <tt literal="">LIMIT</tt>
for some reason.</p>
<p>Now, for actually getting real results:</p>
<pre>&gt;&gt;&gt; r.fetch_row()<br />
(('3','2','0'),)<br />
</pre>
<p>This might look a little odd. The first thing you should know is,
<tt literal="">fetch_row()</tt>
takes some additional parameters. The first one is,
how many rows (<tt literal="">maxrows</tt>)
should be returned. By default, it returns
one row. It may return fewer rows than you asked for, but never
more. If you set <tt literal="">maxrows=0</tt>,
it returns all rows of the result
set. If you ever get an empty tuple back, you ran out of rows.</p>
<p>The second parameter (<tt literal="">how</tt>)
tells it how the row should be
represented. By default, it is zero which means, return as a tuple.
<tt literal="">how=1</tt> means,
return it as a dictionary, where the keys are the
column names, or <tt literal="">table.column</tt>
if there are two columns with the
same name (say, from a join). <tt literal="">how=2</tt> means the same as <tt literal="">how=1</tt>
except that the keys are <em>always</em> <tt literal="">table.column</tt>; this is for
compatibility with the old <tt literal="">Mysqldb</tt> module.</p>
<p>OK, so why did we get a 1-tuple with a tuple inside? Because we
implicitly asked for one row, since we didn't specify <tt literal="">maxrows</tt>.</p>
<p>The other oddity is: Assuming these are numeric columns, why are they
returned as strings? Because MySQL returns all data as strings and
expects you to convert it yourself. This would be a real pain in the
ass, but in fact, <tt literal="">_mysql</tt>
can do this for you. (And <tt literal="">MySQLdb</tt>
does do this for you.) To have automatic type conversion done, you
need to create a type converter dictionary, and pass this to
<tt literal="">connect()</tt> as
the <tt literal="">conv</tt>
keyword parameter.</p>
<p>The keys of <tt literal="">conv</tt>
should be MySQL column types, which in the
C API are <tt literal="">FIELD_TYPE_*</tt>.
You can get these values like this:</p>
<pre>from MySQLdb.constants import FIELD_TYPE<br />
</pre>
<p>By default, any column type that can't be found in <tt literal="">conv</tt> is
returned as a string, which works for a lot of stuff. For our
purposes, we probably want this:</p>
<pre>my_conv = { FIELD_TYPE.LONG: int }<br />
</pre>
<p>This means, if it's a <tt literal="">FIELD_TYPE_LONG</tt>,
call the builtin <tt literal="">int()</tt>
function on it.  Note that <tt literal="">FIELD_TYPE_LONG</tt> is an <tt literal="">INTEGER</tt>
column, which corresponds to a C <tt literal="">long</tt>, which is also the type used
for a normal Python integer. But beware: If it's really an <tt literal="">UNSIGNED
INTEGER</tt> column, this could cause
overflows. For this reason,
<tt literal="">MySQLdb</tt>
actually uses <tt literal="">long()</tt>
to do the conversion. But we'll
ignore this potential problem for now.</p>
<p>Then if you use <tt literal="">db=_mysql.connect(conv=my_conv...)</tt>,
the
results will come back <tt literal="">((3,
2, 0),)</tt>, which
is what you would
expect.</p>
</div>
</div>
<div>
<h1><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id7" id="mysqldb" name="mysqldb">MySQLdb</a></h1>
<p>MySQLdb is a thin Python wrapper around <tt literal="">_mysql</tt> which makes it
compatible with the Python DB API interface (version 2).  In reality,
a fair amount of the code which implements the API is in <tt literal="">_mysql</tt>
for the sake of efficiency.</p>
<p>The DB API specification <a href="http://www.python.org/peps/pep-0249.html">PEP-249</a> should be
your primary guide for
using this module. Only deviations from the spec and other
database-dependent things will be documented here.</p>
<div>
<h2><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id8" id="functions-and-attributes" name="functions-and-attributes">Functions
and attributes</a></h2>
<p>Only a few top-level functions and attributes are defined within
MySQLdb.</p>
<dl><dt>connect(parameters...)</dt><dd>
<p>Constructor for creating a connection to the
database. Returns a Connection Object. Parameters are the
same as for the MySQL C API.  In addition, there are a few
additional keywords that correspond to what you would pass
<tt literal="">mysql_options()</tt>
before connecting. Note that some
parameters must be specified as keyword arguments! The
default value for each parameter is NULL or zero, as
appropriate. Consult the MySQL documentation for more
details. The important parameters are:</p>
<dl docutils=""><dt>host</dt><dd>name of host to connect to. Default: use the local host
via a UNIX socket (where applicable)</dd><dt>user</dt><dd>user to authenticate as. Default: current effective user.</dd><dt>passwd</dt><dd>password to authenticate with. Default: no password.</dd><dt>db</dt><dd>database to use. Default: no default database.</dd><dt>port</dt><dd>TCP port of MySQL server. Default: standard port (3306).</dd><dt>unix_socket</dt><dd>location of UNIX socket. Default: use default location or
TCP for remote hosts.</dd><dt>conv</dt><dd>type conversion dictionary.  Default: a copy of
<tt literal="">MySQLdb.converters.conversions</tt></dd><dt>compress</dt><dd>Enable protocol compression. Default: no compression.</dd><dt>connect_timeout</dt><dd>Abort if connect is not completed within
given number of seconds. Default: no timeout (?)</dd><dt>named_pipe</dt><dd>Use a named pipe (Windows). Default: don't.</dd><dt>init_command</dt><dd>Initial command to issue to server upon
connection. Default: Nothing.</dd><dt>read_default_file</dt><dd>MySQL configuration file to read; see
the MySQL documentation for <tt literal="">mysql_options()</tt>.</dd><dt>read_default_group</dt><dd>Default group to read; see the MySQL
documentation for <tt literal="">mysql_options()</tt>.</dd><dt>cursorclass</dt><dd>cursor class that <tt literal="">cursor()</tt>
uses, unless
overridden. Default: <tt literal="">MySQLdb.cursors.Cursor</tt>.
<em>This
must be a keyword parameter.</em></dd><dt>use_unicode</dt><dd>
<p>If True, CHAR and VARCHAR and TEXT columns are
returned as
Unicode strings, using the configured character set. It is
best to set the default encoding in the server
configuration, or client configuration (read with
read_default_file).  If you change the character set after
connecting (MySQL-4.1 and later), you'll need to put the
correct character set name in connection.charset.</p>
<p>If False, text-like columns are returned as normal strings,
but you can always write Unicode strings.</p>
<p><em>This must be a keyword parameter.</em></p>
</dd><dt>charset</dt><dd>
<p>If present, the connection character set will be
changed
to this character set, if they are not equal. Support for
changing the character set requires MySQL-4.1 and later
server; if the server is too old, UnsupportedError will be
raised. This option implies use_unicode=True, but you can
override this with use_unicode=False, though you probably
shouldn't.</p>
<p>If not present, the default character set is used.</p>
<p><em>This must be a keyword parameter.</em></p>
</dd><dt>sql_mode</dt><dd>
<p>If present, the session SQL mode will be set to the
given
string. For more information on sql_mode, see the MySQL
documentation. Only available for 4.1 and newer servers.</p>
<p>If not present, the session SQL mode will be unchanged.</p>
<p><em>This must be a keyword parameter.</em></p>
</dd><dt>ssl</dt><dd>This parameter takes a dictionary or mapping, where the
keys are parameter names used by the <a href="http://dev.mysql.com/doc/mysql/en/mysql_ssl_set.html">mysql_ssl_set</a>
MySQL
C API call. If this is set, it initiates an SSL connection
to the server; if there is no SSL support in the client,
an exception is raised. <em>This must be a keyword
parameter.</em></dd></dl>
</dd></dl>
<dl><dt>apilevel</dt><dd>String constant stating the supported DB API level. '2.0'</dd><dt>threadsafety</dt><dd>
<p>Integer constant stating the level of thread safety
the
interface supports. This is set to 1, which means: Threads may
share the module.</p>
<p>The MySQL protocol can not handle multiple threads using the
same connection at once. Some earlier versions of MySQLdb
utilized locking to achieve a threadsafety of 2. While this is
not terribly hard to accomplish using the standard Cursor class
(which uses <tt literal="">mysql_store_result()</tt>),
it is complicated by
SSCursor (which uses <tt literal="">mysql_use_result()</tt>;
with the latter you
must ensure all the rows have been read before another query can
be executed.  It is further complicated by the addition of
transactions, since transactions start when a cursor execute a
query, but end when <tt literal="">COMMIT</tt>
or <tt literal="">ROLLBACK</tt>
is executed by
the Connection object.  Two threads simply cannot share a
connection while a transaction is in progress, in addition to
not being able to share it during query execution. This
excessively complicated the code to the point where it just
isn't worth it.</p>
<p>The general upshot of this is: Don't share connections between
threads. It's really not worth your effort or mine, and in the
end, will probably hurt performance, since the MySQL server runs
a separate thread for each connection.  You can certainly do
things like cache connections in a pool, and give those
connections to one thread at a time. If you let two threads use
a connection simultaneously, the MySQL client library will
probably upchuck and die.  You have been warned.</p>
<p>For threaded applications, try using a connection pool.
This can be done using the <a href="http://dustman.net/andy/python/Pool">Pool module</a>.</p>
</dd><dt>charset</dt><dd>The character set used by the connection. In MySQL-4.1 and newer,
it is possible (but not recommended) to change the connection's
character set with an SQL statement. If you do this, you'll also
need to change this attribute. Otherwise, you'll get encoding
errors.</dd><dt>paramstyle</dt><dd>
<p>String constant stating the type of parameter
marker formatting
expected by the interface. Set to 'format' = ANSI C printf
format codes, e.g. '...WHERE name=%s'. If a mapping object is
used for conn.execute(), then the interface actually uses
'pyformat' = Python extended format codes, e.g. '...WHERE
name=%(name)s'. However, the API does not presently allow the
specification of more than one style in paramstyle.</p>
<p>Note that any literal percent signs in the query string passed
to execute() must be escaped, i.e. %%.</p>
<p>Parameter placeholders can <strong>only</strong> be used
to insert column
values. They can <strong>not</strong> be used for other parts of SQL,
such as
table names, statements, etc.</p>
</dd><dt>conv</dt><dd>
<p>A dictionary or mapping which controls how types
are converted
from MySQL to Python and vice versa.</p>
<p>If the key is a MySQL type (from <tt literal="">FIELD_TYPE.*</tt>), then the value
can be either:</p>
<ul>
    <li>a callable object which takes a string argument (the MySQL
    value),' returning a Python value</li>
    <li>a sequence of 2-tuples, where the first value is a combination
    of flags from <tt literal="">MySQLdb.constants.FLAG</tt>,
    and the second value
    is a function as above. The sequence is tested until the flags
    on the field match those of the first value. If both values
    are None, then the default conversion is done. Presently this
    is only used to distinquish TEXT and BLOB columns.</li>
</ul>
<p>If the key is a Python type or class, then the value is a
callable Python object (usually a function) taking two arguments
(value to convert, and the conversion dictionary) which converts
values of this type to a SQL literal string value.</p>
<p>This is initialized with reasonable defaults for most
types. When creating a Connection object, you can pass your own
type converter dictionary as a keyword parameter. Otherwise, it
uses a copy of <tt literal="">MySQLdb.converters.conversions</tt>.
Several
non-standard types are returned as strings, which is how MySQL
returns all columns. For more details, see the built-in module
documentation.</p>
</dd></dl>
</div>
<div>
<h2><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id9" id="connection-objects" name="connection-objects">Connection Objects</a></h2>
<p>Connection objects are returned by the <tt literal="">connect()</tt> function.</p>
<dl><dt>commit()</dt><dd>If the database and the tables support transactions, this
commits the current transaction; otherwise this method
successfully does nothing.</dd><dt>rollback()</dt><dd>If the database and tables support transactions, this rolls back
(cancels) the current transaction; otherwise a
<tt literal="">NotSupportedError</tt>
is raised.</dd><dt>cursor([cursorclass])</dt><dd>MySQL does not support cursors; however, cursors are easily
emulated.  You can supply an alternative cursor class as an
optional parameter.  If this is not present, it defaults to the
value given when creating the connection object, or the standard
<tt literal="">Cursor</tt> class.
Also see the additional supplied cursor
classes in the usage section.</dd></dl>
<p>There are many more methods defined on the connection object which
are MySQL-specific. For more information on them, consult the internal
documentation using <tt literal="">pydoc</tt>.</p>
</div>
<div>
<h2><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id10" id="cursor-objects" name="cursor-objects">Cursor Objects</a></h2>
<dl><dt>callproc(procname, args)</dt><dd>
<p>Calls stored procedure procname with the sequence
of arguments
in args. Returns the original arguments. Stored procedure
support only works with MySQL-5.0 and newer.</p>
<p><strong>Compatibility note:</strong> <a href="http://www.python.org/peps/pep-0249.html">PEP-249</a> specifies
that if there are
OUT or INOUT parameters, the modified values are to be
returned. This is not consistently possible with MySQL. Stored
procedure arguments must be passed as server variables, and
can only be returned with a SELECT statement. Since a stored
procedure may return zero or more result sets, it is impossible
for MySQLdb to determine if there are result sets to fetch
before the modified parmeters are accessible.</p>
<p>The parameters are stored in the server as @_*procname*_*n*,
where <em>n</em> is the position of the parameter. I.e., if you
cursor.callproc('foo', (a, b, c)), the parameters will be
accessible by a SELECT statement as @_foo_0, @_foo_1, and
@_foo_2.</p>
<p><strong>Compatibility note:</strong> It appears that the
mere act of
executing the CALL statement produces an empty result set, which
appears after any result sets which might be generated by the
stored procedure. Thus, you will always need to use nextset() to
advance result sets.</p>
</dd><dt>close()</dt><dd>Closes the cursor. Future operations raise <tt literal="">ProgrammingError</tt>.
If you are using server-side cursors, it is very important to
close the cursor when you are done with it and before creating a
new one.</dd><dt>info()</dt><dd>Returns some information about the last query. Normally
you don't need to check this. If there are any MySQL
warnings, it will cause a Warning to be issued through
the Python warning module. By default, Warning causes a
message to appear on the console. However, it is possible
to filter these out or cause Warning to be raised as exception.
See the MySQL docs for <tt literal="">mysql_info()</tt>,
and the Python warning
module. (Non-standard)</dd><dt>setinputsizes()</dt><dd>Does nothing, successfully.</dd><dt>setoutputsizes()</dt><dd>Does nothing, successfully.</dd><dt>nextset()</dt><dd>
<p>Advances the cursor to the next result set,
discarding the remaining
rows in the current result set. If there are no additional result
sets, it returns None; otherwise it returns a true value.</p>
<p>Note that MySQL doesn't support multiple result sets
until 4.1.</p>
</dd></dl>
</div>
<div>
<h2><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id11" id="some-examples" name="some-examples">Some examples</a></h2>
<p>The <tt literal="">connect()</tt>
method works nearly the same as with <a href="http://mysql-python.sourceforge.net/MySQLdb.html#mysql">_mysql</a>:</p>
<pre>import MySQLdb<br />
db=MySQLdb.connect(passwd="moonpie",db="thangs")<br />
</pre>
<p>To perform a query, you first need a cursor, and then you can execute
queries on it:</p>
<pre>c=db.cursor()<br />
max_price=5<br />
c.execute("""SELECT spam, eggs, sausage FROM breakfast<br />
WHERE price &lt; %s""", (max_price,))<br />
</pre>
<p>In this example, <tt literal="">max_price=5</tt>
Why, then, use <tt literal="">%s</tt>
in the
string? Because MySQLdb will convert it to a SQL literal value, which
is the string '5'. When it's finished, the query will actually say,
"...WHERE price &lt; 5".</p>
<p>Why the tuple? Because the DB API requires you to pass in any
parameters as a sequence. Due to the design of the parser, (max_price)
is interpreted as using algebraic grouping and simply as max_price and
not a tuple. Adding a comma, i.e. (max_price,) forces it to make a
tuple.</p>
<p>And now, the results:</p>
<pre>&gt;&gt;&gt; c.fetchone()<br />
(3L, 2L, 0L)<br />
</pre>
<p>Quite unlike the <tt literal="">_mysql</tt>
example, this returns a single tuple,
which is the row, and the values are properly converted by default...
except... What's with the L's?</p>
<p>As mentioned earlier, while MySQL's INTEGER column translates
perfectly into a Python integer, UNSIGNED INTEGER could overflow, so
these values are converted to Python long integers instead.</p>
<p>If you wanted more rows, you could use <tt literal="">c.fetchmany(n)</tt> or
<tt literal="">c.fetchall()</tt>.
These do exactly what you think they do. On
<tt literal="">c.fetchmany(n)</tt>,
the <tt literal="">n</tt> is
optional and defaults to
<tt literal="">c.arraysize</tt>,
which is normally 1. Both of these methods return a
sequence of rows, or an empty sequence if there are no more rows.  If
you use a weird cursor class, the rows themselves might not be tuples.</p>
<p>Note that in contrast to the above, <tt literal="">c.fetchone()</tt> returns <tt literal="">None</tt>
when there are no more rows to fetch.</p>
<p>The only other method you are very likely to use is when you have to
do a multi-row insert:</p>
<pre>c.executemany(<br />
"""INSERT INTO breakfast (name, spam, eggs, sausage, price)<br />
VALUES (%s, %s, %s, %s, %s)""",<br />
[<br />
("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),<br />
("Not So Much Spam Plate", 3, 2, 0, 3.95 ),<br />
("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )<br />
] )<br />
</pre>
<p>Here we are inserting three rows of five values. Notice that there is
a mix of types (strings, ints, floats) though we still only use
<tt literal="">%s</tt>. And also
note that we only included format strings for one
row. MySQLdb picks those out and duplicates them for each row.</p>
</div>
</div>
<div>
<h1><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id12" id="using-and-extending" name="using-and-extending">Using and extending</a></h1>
<p>In general, it is probably wise to not directly interact with the DB
API except for small applicatons. Databases, even SQL databases, vary
widely in capabilities and may have non-standard features. The DB API
does a good job of providing a reasonably portable interface but some
methods are non-portable. Specifically, the parameters accepted by
<tt literal="">connect()</tt> are
completely implementation-dependent.</p>
<p>If you believe your application may need to run on several different
databases, the author recommends the following approach, based on
personal experience: Write a simplified API for your application which
implements the specific queries and operations your application needs
to perform. Implement this API as a base class which should be have
few database dependencies, and then derive a subclass from this which
implements the necessary dependencies. In this way, porting your
application to a new database should be a relatively simple matter of
creating a new subclass, assuming the new database is reasonably
standard.</p>
<p>Because MySQLdb's Connection and Cursor objects are written in
Python,
you can easily derive your own subclasses. There are several Cursor
classes in MySQLdb.cursors:</p>
<dl><dt>BaseCursor</dt><dd>The base class for Cursor objects.  This does not raise Warnings.</dd><dt>CursorStoreResultMixIn</dt><dd>Causes the Cursor to use the <tt literal="">mysql_store_result()</tt> function to
get the query result. The entire result set is stored on the
client side.</dd><dt>CursorUseResultMixIn</dt><dd>Causes the cursor to use the <tt literal="">mysql_use_result()</tt> function to
get the query result. The result set is stored on the server side
and is transferred row by row using fetch operations.</dd><dt>CursorTupleRowsMixIn</dt><dd>Causes the cursor to return rows as a tuple of the column values.</dd></dl>
<p>CursorDictRowsMixIn</p>
<blockquote>
Causes the cursor to return rows as a dictionary, where the keys
are column names and the values are column values. Note that if
the column names are not unique, i.e., you are selecting from two
tables that share column names, some of them will be rewritten as
<tt literal="">table.column</tt>.
This can be avoided by using the SQL <tt literal="">AS</tt>
keyword. (This is yet-another reason not to use <tt literal="">*</tt> in SQL
queries, particularly where <tt literal="">JOIN</tt> is involved.)</blockquote>
<dl><dt>Cursor</dt><dd>The default cursor class. This class is composed of
<tt literal="">CursorWarningMixIn</tt>,
<tt literal="">CursorStoreResultMixIn</tt>,
<tt literal="">CursorTupleRowsMixIn,</tt>
and <tt literal="">BaseCursor</tt>,
i.e. it raises
<tt literal="">Warning</tt>, uses
<tt literal="">mysql_store_result()</tt>,
and returns rows as
tuples.</dd><dt>DictCursor</dt><dd>Like <tt literal="">Cursor</tt>
except it returns rows as dictionaries.</dd><dt>SSCursor</dt><dd>A "server-side" cursor. Like <tt literal="">Cursor</tt> but uses
<tt literal="">CursorUseResultMixIn</tt>.
Use only if you are dealing with
potentially large result sets.</dd><dt>SSDictCursor</dt><dd>Like <tt literal="">SSCursor</tt>
except it returns rows as dictionaries.</dd></dl>
</div>
<h1><a href="http://mysql-python.sourceforge.net/MySQLdb.html#id13" id="embedded-server" name="embedded-server">Embedded Server</a></h1>
<p>Instead of connecting to a stand-alone server over the network,
the embedded server support lets you run a full server right in
your Python code or application server.</p>
<p>If you have built MySQLdb with embedded server support, there
are two additional functions you will need to make use of:</p>
<blockquote>
<dl><dt>server_init(args, groups)</dt><dd>
<p>Initialize embedded server. If this client is not
linked against
the embedded server library, this function does nothing.</p>
<dl docutils=""><dt>args</dt><dd>sequence of command-line arguments</dd><dt>groups</dt><dd>sequence of groups to use in defaults files</dd></dl>
</dd><dt>server_end()</dt><dd>Shut down embedded server. If not using an embedded server, this
does nothing.</dd></dl>
</blockquote>
<p>See the MySQL documentation for more information on the embedded
server.</p>
<table field-list="" frame="void" rules="none">
    <col>
    <col>
    <tbody valign="top">
        <tr>
            <th>Title:</th>
            <td>MySQLdb: a Python interface for MySQL</td>
        </tr>
        <tr>
            <th>Author:</th>
            <td>Andy Dustman</td>
        </tr>
        <tr>
            <th>Version:</th>
            <td>$Revision: 421 $</td>
        </tr>
    </tbody>
</table>
<img src ="http://www.blogjava.net/sealyu/aggbug/321217.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2010-05-17 23:56 <a href="http://www.blogjava.net/sealyu/archive/2010/05/17/321217.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>如何在Mac OS X系统中启用MySQL(转)</title><link>http://www.blogjava.net/sealyu/archive/2010/05/16/321082.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Sun, 16 May 2010 01:38:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2010/05/16/321082.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/321082.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2010/05/16/321082.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/321082.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/321082.html</trackback:ping><description><![CDATA[<p>随着网络日益发展还有os x用户的增多，有可能会需要在自己的x系统中运行mysql+php环境，比如架设网站或者测试之类。简单步骤如下：</p>
<p>　　1、下载MySQL 5.x 发行版 ，解压并安装映像中的两个安装包文件。</p>
<p>　　a. mysql-5.x-osx10.6_x86_64.pkg －mysql 5.x 标准版安装</p>
<p>　　b.
MySQLStartupItem.pkg－mysql启动项目，可以上你的电脑在启动系统时自动运行mysql服务。它安装在/Library
/StartupItems/MySQL/，如果你不想系统启动时运行mysql服务，请不要安装。如果你在安装后又不想使用，请删除/Library
/StartupItems/MySQL/这个目录。</p>
<p>　　启动mysql：</p>
<p>　　2、如果你已经安装了MySQLStartupItem.pkg，重新启动电脑即可。</p>
<p>　　3、如果你有安装MySQLStartupItem.pkg或者不想启动电脑，运行：应用程序－实用程序－终端程序，在终端中输入命令：</p>
<p>　　sudo /Library/StartupItems/MySQL/MySQL start</p>
<p>　　然后输入你的系统管理员密码，如果没有设定密码就直接回车。</p>
<p>　　关闭mysql服务：</p>
<p>　　终端中输入命令：sudo /Library/StartupItems/MySQL/MySQL stop</p>
<p>　　然后输入你的系统管理员密码，如果没有设定密码就直接回车。</p>
<p>　　mysql root账户密码：</p>
<p>　　mysql root密码初始值是空。这样虽然没有问题。但很不安全。建议你更改root用户密码。注意：mysql
root用户和系统中的root用户是不一样的。是完全两个不同的用户。</p>
<p>　　更改mysql root密码请在终端中输入命令：</p>
<p>　　/usr/local/mysql/bin/mysqladmin -u root password 新密码</p>
<p>　　同时你也可以随时使用这条命令更改你的密码。</p>
<p>　　4、下载x版mysql数据库管理工具</p>
<p>　　这是一个运行在mac os
x系统中的mysql数据库管理软件，支持本地及远程数据库管理。并且还是免费的。这个程序的优点是完全CGI界面。并且密码是保存在本机上的。相对比较
安全。</p>
<img src ="http://www.blogjava.net/sealyu/aggbug/321082.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2010-05-16 09:38 <a href="http://www.blogjava.net/sealyu/archive/2010/05/16/321082.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title> Software caused connection abort: recv failed</title><link>http://www.blogjava.net/sealyu/archive/2010/04/15/318384.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Wed, 14 Apr 2010 21:58:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2010/04/15/318384.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/318384.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2010/04/15/318384.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/318384.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/318384.html</trackback:ping><description><![CDATA[Today i met a problem:&nbsp; Software caused connection abort: recv failed<br />
<br />
Solution: Uninstall ipv6 from Network management.
<img src ="http://www.blogjava.net/sealyu/aggbug/318384.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2010-04-15 05:58 <a href="http://www.blogjava.net/sealyu/archive/2010/04/15/318384.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>数据库的动态字段问题</title><link>http://www.blogjava.net/sealyu/archive/2010/03/18/315797.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Thu, 18 Mar 2010 07:59:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2010/03/18/315797.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/315797.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2010/03/18/315797.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/315797.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/315797.html</trackback:ping><description><![CDATA[<div>Sealyu &nbsp;2010－3－18</div>
<div><br />
</div>
在项目中经常会碰到这样的问题： 用户要求他们的产品等实体的属性是可定制的。比如：产品的数量、高度、重量等属性，都是可以在后台增删该查的。在这种情况下，使用java建立实体就遇到问题了，因为数据库中的字段是不定的。 这种情况在一些单据、试卷等地方是很常见的。
<div>1。目前为止，没有发现比较完美的解决方法。 之前项目中遇到了一次动态生成单据的情况，主要是通过使用几张表来存储表的结构和字段信息来实现。 这种情况下，实现查询和报表等功能时就会受到影响。 具体方法跟下面这位的类似：
</div>
<div>
<div style="background-color: #eeeeee; font-size: 13px; border-left-color: #cccccc; padding-right: 5px; padding-bottom: 4px; padding-left: 4px; padding-top: 4px; width: 98%; word-break: break-all; "><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000; ">我在给一家打字公司开发一个将表单的内容输入数据库的程序。表单中可能有简单的送货收据（20多个字段），可能有民意调查的表格（50多个字段），可能有保险公司的用户登记表（100多个字段）。讨厌的是这样的表单可能又几百种。&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;我设计的数据库如下：&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;表单的种类表（表1）：&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Form_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//表单的种类ID&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Form_Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//表单的名称&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;某一个表单的字段表（表2）&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Field_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//字段的ID&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Field_Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//字段的名称&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Form_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//表单的种类ID，与表1连接&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;具体的某一个表单表（表3）&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sheet_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//具体的某一个表单的ID&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Client_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//这个表单所属的客户ID，与客户表连接&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;某一个表单的字段内容表（表4）&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Field_Value_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//字段的内容ID&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Field_Value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//字段的内容&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Field_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//字段的ID，与表2连接&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sheet_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//具体的某一个表单的ID，与表3连接&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;每增加了一种新的表单时，在表1和表2中添加如下记录：&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;表1：Form_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Form_Name&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A001&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;送货单&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;表2：Field_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Field_Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Form_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f0001&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;发货日期&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A001&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f0002&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;发货人&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A001&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f0003&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货人地址&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A001&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;这样，当某一个打字公司的客户要求输入这个&#8220;送货单&#8221;时，每输入一个送货单（即表单表3），表3和表4添加如下记录：（每输入一个送货单之类的表单，表3和表4都添加数据）&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;表3：Sheet_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Client_ID&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;S001&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0000001&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;表4：Field_Value_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Field_Value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Field_ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sheet_ID&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;V0001&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2001.5.8&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f0001&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;S001&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;V0002&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;张三&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f0002&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;S001&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;V0003&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;大连市西岗区&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f0003&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;S001&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;打字公司根据具体的某一个表单的ID（Sheet_ID），结合4个表提取客户ID、表单种类名称、字段名称和字段内容存入另外的数据库。 &nbsp;&nbsp;</span></div>
</div>
<div>2。还看到过一种情况，是只用一个长字符串字段，利用xml的格式来存储对应的结构，同时在java中使用xml2db等工具来解析。这种情况下，查询和报表功能同样不好实现。同时，xml节点的增删该查也不太方便。</div>
<div>3。最后一种方法，是直接使用数据库来实现。前几天看到DB2 9中已经支持对XML格式数据的存储和查询。使用XQUERY来配套实现查询。不过这种方法对数据库的依赖性强，目前为止，还没发现有其他数据库提供这种功能。</div>
<div><br />
</div>
<img src ="http://www.blogjava.net/sealyu/aggbug/315797.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2010-03-18 15:59 <a href="http://www.blogjava.net/sealyu/archive/2010/03/18/315797.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>XMLTABLE by example, Part 2: Common scenarios for using XMLTABLE with DB2</title><link>http://www.blogjava.net/sealyu/archive/2010/02/24/313810.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Wed, 24 Feb 2010 08:43:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2010/02/24/313810.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/313810.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2010/02/24/313810.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/313810.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/313810.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: Get the most out of this SQL/XML functionVitor Rodrigues (vrodrig@us.ibm.com), DB2 pureXML  Technical Enablement, IBMVitorRodrigues is a software developer at the IBM Silicon Valley Lab. He...&nbsp;&nbsp;<a href='http://www.blogjava.net/sealyu/archive/2010/02/24/313810.html'>阅读全文</a><img src ="http://www.blogjava.net/sealyu/aggbug/313810.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2010-02-24 16:43 <a href="http://www.blogjava.net/sealyu/archive/2010/02/24/313810.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>spring的DriverManagerDataSource与apache的BasicDataSource（转）</title><link>http://www.blogjava.net/sealyu/archive/2010/02/02/311728.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Tue, 02 Feb 2010 14:04:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2010/02/02/311728.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/311728.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2010/02/02/311728.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/311728.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/311728.html</trackback:ping><description><![CDATA[情况是这样的。。。
<br />
<br />
2008-3-18 1:08:26 org.apache.tomcat.util.threads.ThreadPool logFull
<br />
严重: All threads (150) are currently busy, waiting. Increase maxThreads (150) or check the servlet status
<br />
<br />
重新启动服务器之后，问题依然存在。
<br />
分析得出以下可能情况
<br />
1.连接数达到了150的最大上限
<br />
2.服务器端响应用户请求的时间过长导致
<br />
3.连接池的配置数出了问题
<br />
<br />
分析：
<br />
1.1个用户访问是OK的，当用2个用户对localhost进行访问，所以根本不可能达到并发访问线程的150的上限，所以应该不是数据库的原因,排除了第一种可能
<br />
2.之前访问的JSP已经经过多次访问，所以不可能是第一次访问编译，运行而导致的请求时间过长的原因，第二情况也否定。
<br />
<br />
<strong>到此，经过分析可以确定的是连接池出了问题...</strong>
<br />
<br />
首先有2个知识点需要再弄的更清楚一些
<br />
<br />
<strong>DriverManager与DataSource&nbsp; 连接数据库有何区别?</strong>
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DriverManager传统的jdbc连接，通过Class.forName("XXX"),的办法注册之后，就可以DriverManager.getConnection()获得连接了。
<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DataSource是建立在JNDI服务基础上的,需要application
server配置datasource.首先需要注册一个DataSource(一般在/META-INF/context.xml下)然后在
web.xml文件中引用这个DataSource,就可以DataSource.getConnection()获得连接,具体操作参考(tomcat
目录里的JNDI Resources小节)
<br />
<br />
<strong>DataSource 与 DBCP pool(连接池) 的区别？</strong>
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; J2EE
服务器启动时会建立一定数量的池连接，并一直维持不少于此数目的池连接。客户端程序需要连接时，池驱动程序会返回一个未使用的池连接并将其表记为忙。如果
当前没有空闲连接，池驱动程序就新建一定数量的连接，新建连接的数量有配置参数决定。当使用的池连接调用完成后，池驱动程序将此连接表记为空闲，其他调用
就可以使用这个连接。
<br />
相当于是优化了DataSource的一种工具
<br />
<br />
跟数据库连接的部分是通过Spring的DataSource JDBC连接的,配置的XML内容如下:
<br />
<div>
<div>
<div>Xml代码 <embed src="http://jueforever.javaeye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=%3Cbean%20id%3D%22propertyConfigurer%22%20%0Aclass%3D%22org.springframework.beans.factory.config.PropertyPlaceholderConfigurer%22%3E%0A%3C!--PropertyPlaceholderConfigurer%E7%B1%BB%E6%9D%A5%E8%AF%BB%E5%8F%96xxx.properties%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E4%BF%A1%E6%81%AF%2C%E4%BB%A5key%E5%92%8Cvalue%E7%9A%84%E5%BD%A2%E5%BC%8F--%3E%0A%3Cproperty%20name%3D%22locations%22%3E%0A%20%20%20%20%3Clist%3E%0A%20%20%20%20%20%20%20%20%3Cvalue%3E%0A%20%20%20%20%20%20%20%20%20%20%2FWEB-INF%2Fclasses%2Fconfig%2Fpkm%2Fenvironment%2Fjdbc.properties%0A%20%20%20%20%20%20%20%20%3C%2Fvalue%3E%0A%20%20%20%20%20%20%20%20%3Cvalue%3E%0A%20%20%20%20%20%20%20%20%20%20%3C!--%E5%A4%9A%E4%B8%AAxxx.properties%E6%96%87%E4%BB%B6--%3E%0A%20%20%20%20%20%20%20%20%3C%2Fvalue%3E%0A%20%20%20%20%3C%2Flist%3E%0A%3C%2Fproperty%3E%0A%3C%2Fbean%3E%0A%0A%3C!--%E4%BA%8B%E5%AE%9E%E4%B8%8A%E6%98%AF%E5%9B%A0%E4%B8%BADriverManagerDataSource%E5%BB%BA%E7%AB%8B%E8%BF%9E%E6%8E%A5%E6%98%AF%E5%8F%AA%E8%A6%81%E6%9C%89%E8%BF%9E%E6%8E%A5%E5%B0%B1%E6%96%B0%E5%BB%BA%E4%B8%80%E4%B8%AAconnection%2C%E6%A0%B9%E6%9C%AC%E6%B2%A1%E6%9C%89%E8%BF%9E%E6%8E%A5%E6%B1%A0%E7%9A%84%E4%BD%9C%E7%94%A8--%3E%0A%3C!--%E4%B8%A4%E7%A7%8D%E4%B8%8D%E5%90%8C%E7%9A%84DataSource--%3E%0A%3C!--%E5%8D%95%E7%BA%AF%E7%9A%84DataSource--%3E%0A%3Cbean%20id%3D%22pkmDataSource%22%20%0Aclass%3D%22org.springframework.jdbc.datasource.DriverManagerDataSource%22%3E%0A%20%20%20%20%3Cproperty%20name%3D%22driverClassName%22%3E%0A%20%20%20%20%20%20%20%20%3Cvalue%3E%24%7Bpkm.jdbc.driverClassName%7D%3C%2Fvalue%3E%0A%20%20%20%20%20%20%20%20%3C!--%24%7Bpkm.jdbc.driverClassName%7D%E6%98%AFjdbc.properties%E6%96%87%E4%BB%B6%20%E4%B8%AD%E7%9A%84key--%3E%0A%20%20%20%20%3C%2Fproperty%3E%0A%20%20%20%20%3Cproperty%20name%3D%22url%22%3E%0A%20%20%20%20%20%20%20%20%3Cvalue%3E%24%7Bpkm.jdbc.url%7D%3C%2Fvalue%3E%0A%20%20%20%20%3C%2Fproperty%3E%0A%20%20%20%20%3Cproperty%20name%3D%22username%22%3E%0A%20%20%20%20%20%20%20%20%3Cvalue%3E%24%7Bpkm.jdbc.username%7D%3C%2Fvalue%3E%0A%20%20%20%20%3C%2Fproperty%3E%0A%20%20%20%20%3Cproperty%20name%3D%22password%22%3E%0A%20%20%20%20%20%20%20%20%3Cvalue%3E%24%7Bpkm.jdbc.password%7D%3C%2Fvalue%3E%0A%20%20%20%20%3C%2Fproperty%3E%0A%3C%2Fbean%3E%0A%0A%3C!--%E8%BF%9E%E6%8E%A5%E6%B1%A0--%3E%0A%3Cbean%20id%3D%22pkmDataSource%22%20%0Aclass%3D%22org.apache.commons.dbcp.BasicDataSource%22%20destroy-method%3D%22close%22%20lazy-init%3D%22false%22%3E%0A%20%20%20%20%3Cproperty%20name%3D%22driverClassName%22%20value%3D%22%24%7Bpkm.jdbc.driverClassName%7D%22%2F%3E%0A%20%20%20%20%3Cproperty%20name%3D%22url%22%20value%3D%22%24%7Bpkm.jdbc.url%7D%22%2F%3E%0A%20%20%20%20%3Cproperty%20name%3D%22username%22%20value%3D%22%24%7Bpkm.jdbc.username%7D%22%2F%3E%0A%20%20%20%20%3Cproperty%20name%3D%22password%22%20value%3D%22%24%7Bpkm.jdbc.password%7D%22%2F%3E%0A%20%20%20%20%3Cproperty%20name%3D%22initialSize%22%20value%3D%225%22%2F%3E%0A%20%20%20%20%3Cproperty%20name%3D%22maxActive%22%20value%3D%2210%22%2F%3E%0A%20%20%20%20%3Cproperty%20name%3D%22maxWait%22%20value%3D%2260000%22%2F%3E%0A%20%20%20%20%3Cproperty%20name%3D%22poolPreparedStatements%22%20value%3D%22true%22%2F%3E%20%20%0A%3C%2Fbean%3E" quality="high" allowscriptaccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" width="14" height="15"></div>
</div>
<ol start="1">
    <li>&lt;bean&nbsp;id="propertyConfigurer"&nbsp;&nbsp;&nbsp;</li>
    <li>class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;&nbsp;&nbsp;</li>
    <li>&lt;!--PropertyPlaceholderConfigurer类来读取xxx.properties配置文件信息,以key和value的形式--&gt;&nbsp;&nbsp;</li>
    <li>&lt;property&nbsp;name="locations"&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;list&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/WEB-INF/classes/config/pkm/environment/jdbc.properties&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/value&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;!--多个xxx.properties文件--&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/value&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;/list&gt;&nbsp;&nbsp;</li>
    <li>&lt;/property&gt;&nbsp;&nbsp;</li>
    <li>&lt;/bean&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;</li>
    <li>&lt;!--事实上是因为DriverManagerDataSource建立连接是只要有连接就新建一个connection,根本没有连接池的作用--&gt;&nbsp;&nbsp;</li>
    <li>&lt;!--两种不同的DataSource--&gt;&nbsp;&nbsp;</li>
    <li>&lt;!--单纯的DataSource--&gt;&nbsp;&nbsp;</li>
    <li>&lt;bean&nbsp;id="pkmDataSource"&nbsp;&nbsp;&nbsp;</li>
    <li>class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="driverClassName"&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;${pkm.jdbc.driverClassName}&lt;/value&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;!--${pkm.jdbc.driverClassName}是jdbc.properties文件&nbsp;中的key--&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;/property&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="url"&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;${pkm.jdbc.url}&lt;/value&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;/property&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="username"&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;${pkm.jdbc.username}&lt;/value&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;/property&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="password"&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;${pkm.jdbc.password}&lt;/value&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;/property&gt;&nbsp;&nbsp;</li>
    <li>&lt;/bean&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;</li>
    <li>&lt;!--连接池--&gt;&nbsp;&nbsp;</li>
    <li>&lt;bean&nbsp;id="pkmDataSource"&nbsp;&nbsp;&nbsp;</li>
    <li>class="org.apache.commons.dbcp.BasicDataSource"&nbsp;destroy-method="close"&nbsp;lazy-init="false"&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="driverClassName"&nbsp;value="${pkm.jdbc.driverClassName}"/&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="url"&nbsp;value="${pkm.jdbc.url}"/&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="username"&nbsp;value="${pkm.jdbc.username}"/&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="password"&nbsp;value="${pkm.jdbc.password}"/&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="initialSize"&nbsp;value="5"/&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="maxActive"&nbsp;value="10"/&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="maxWait"&nbsp;value="60000"/&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="poolPreparedStatements"&nbsp;value="true"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;</li>
    <li>&lt;/bean&gt;&nbsp;&nbsp;</li>
</ol>
</div>
<pre style="display: none;" name="code" class="xml">&lt;bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;
&lt;!--PropertyPlaceholderConfigurer类来读取xxx.properties配置文件信息,以key和value的形式--&gt;
&lt;property name="locations"&gt;
&lt;list&gt;
&lt;value&gt;
/WEB-INF/classes/config/pkm/environment/jdbc.properties
&lt;/value&gt;
&lt;value&gt;
&lt;!--多个xxx.properties文件--&gt;
&lt;/value&gt;
&lt;/list&gt;
&lt;/property&gt;
&lt;/bean&gt;
&lt;!--事实上是因为DriverManagerDataSource建立连接是只要有连接就新建一个connection,根本没有连接池的作用--&gt;
&lt;!--两种不同的DataSource--&gt;
&lt;!--单纯的DataSource--&gt;
&lt;bean id="pkmDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
&lt;property name="driverClassName"&gt;
&lt;value&gt;${pkm.jdbc.driverClassName}&lt;/value&gt;
&lt;!--${pkm.jdbc.driverClassName}是jdbc.properties文件 中的key--&gt;
&lt;/property&gt;
&lt;property name="url"&gt;
&lt;value&gt;${pkm.jdbc.url}&lt;/value&gt;
&lt;/property&gt;
&lt;property name="username"&gt;
&lt;value&gt;${pkm.jdbc.username}&lt;/value&gt;
&lt;/property&gt;
&lt;property name="password"&gt;
&lt;value&gt;${pkm.jdbc.password}&lt;/value&gt;
&lt;/property&gt;
&lt;/bean&gt;
&lt;!--连接池--&gt;
&lt;bean id="pkmDataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" lazy-init="false"&gt;
&lt;property name="driverClassName" value="${pkm.jdbc.driverClassName}"/&gt;
&lt;property name="url" value="${pkm.jdbc.url}"/&gt;
&lt;property name="username" value="${pkm.jdbc.username}"/&gt;
&lt;property name="password" value="${pkm.jdbc.password}"/&gt;
&lt;property name="initialSize" value="5"/&gt;
&lt;property name="maxActive" value="10"/&gt;
&lt;property name="maxWait" value="60000"/&gt;
&lt;property name="poolPreparedStatements" value="true"/&gt;
&lt;/bean&gt;</pre>
<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 所以问题就出在这里,当使用BasicDataSource后问题不在出现,所以是连接数量造成的,在访问数量大,并发的情况下,毫无疑问是要选择连接池的,因为有连接池的功能,无论是效率还是在资源利用率上都优于DriverManagerDataSource
<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 从而从根本上了解了spring的DriverManagerDataSource与apacheBasicDataSource之间的区别.
<br />
<br />
有时候可能需要配置Jndi服务
<br />
<div>
<div>
<div>Xml代码 <embed src="http://jueforever.javaeye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=%3Cbean%20id%3D%22pkmDataSource%22%20%0Aclass%3D%22org.springframework.jndi.JndiObjectFactoryBean%22%3E%0A%20%20%20%20%3Cproperty%20name%3D%22jndiName%22%20value%3D%22pkmDataSource%22%2F%3E%20%0A%3C%2Fbean%3E%0A%3C!--%0A%E8%BF%99%E6%A0%B7%E7%9A%84%E8%AF%9D%E9%83%A8%E7%BD%B2%E7%9A%84%E6%97%B6%E5%80%99%EF%BC%8C%E9%9C%80%E8%A6%81%E5%9C%A8%E5%AE%B9%E5%99%A8%E4%B8%AD%EF%BC%88tomcat%2Cweblogic%EF%BC%89%E9%85%8D%E7%BD%AEJDBC%20Connection%20Pool(DBCP)%E8%BF%9E%E6%8E%A5%E6%B1%A0%0A--%3E%0A" quality="high" allowscriptaccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" width="14" height="15"></div>
</div>
<ol start="1">
    <li>&lt;bean&nbsp;id="pkmDataSource"&nbsp;&nbsp;&nbsp;</li>
    <li>class="org.springframework.jndi.JndiObjectFactoryBean"&gt;&nbsp;&nbsp;</li>
    <li>&nbsp;&nbsp;&nbsp;&nbsp;&lt;property&nbsp;name="jndiName"&nbsp;value="pkmDataSource"/&gt;&nbsp;&nbsp;&nbsp;</li>
    <li>&lt;/bean&gt;&nbsp;&nbsp;</li>
    <li>&lt;!--&nbsp;</li>
    <li>这样的话部署的时候，需要在容器中（tomcat,weblogic）配置JDBC&nbsp;Connection&nbsp;Pool(DBCP)连接池&nbsp;</li>
    <li>--&gt;&nbsp;&nbsp;</li>
</ol>
</div>
<pre style="display: none;" name="code" class="xml">&lt;bean id="pkmDataSource"
class="org.springframework.jndi.JndiObjectFactoryBean"&gt;
&lt;property name="jndiName" value="pkmDataSource"/&gt;
&lt;/bean&gt;
&lt;!--
这样的话部署的时候，需要在容器中（tomcat,weblogic）配置JDBC Connection Pool(DBCP)连接池
--&gt;
</pre>
<br />
<br />
<strong>这三种连接方式常常使用，也容易混淆，选择其中的某一种，就需要看具体环境来配置了。</strong>
<br />
<br />
<span style="font-size: medium;">PS：jdbc.properties文件中的配置如下</span>
<br />
<div>
<div>
<div>Properties代码 <embed src="http://jueforever.javaeye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=pkm.jdbc.driverClassName%3Doracle.jdbc.OracleDriver%0Apkm.jdbc.url%3Djdbc%5C%3Aoracle%5C%3Athin%5C%3A%40109.52.20.31%5C%3A1521%5C%3Aorcl%3C!--%E6%8A%8A%E7%AC%A6%E5%8F%B7%E5%81%9A%E8%BD%AC%E8%AF%91--%3E%0Apkm.jdbc.name%3Dpkmuser%0Apkm.jdbc.password%3Ddbl0gin%0Apkm.jdbc.dataSource%3DpkmDataSource" quality="high" allowscriptaccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" width="14" height="15"></div>
</div>
<ol start="1">
    <li>pkm.jdbc.driverClassName=oracle.jdbc.OracleDriver&nbsp;&nbsp;</li>
    <li>pkm.jdbc.url=jdbc":oracle":thin":@109.52.20.31":1521":orcl&lt;!--把符号做转译--&gt;&nbsp;&nbsp;</li>
    <li>pkm.jdbc.name=pkmuser&nbsp;&nbsp;</li>
    <li>pkm.jdbc.password=dbl0gin&nbsp;&nbsp;</li>
    <li>pkm.jdbc.dataSource=pkmDataSource&nbsp;&nbsp;</li>
</ol>
<br />
<h1>                    关于Spring整合发现的一些问题。
<cite><a href="javascript:d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(saveit=window.open('http://wz.csdn.net/storeit.aspx?t='+escape(d.title)+'&amp;u='+escape(d.location.href)+'&amp;c='+escape(t),'saveit','scrollbars=no,width=590,height=300,left=75,top=20,status=no,resizable=yes'));saveit.focus();" class="fav_csdnstylebykimi" title="收藏到我的网摘中，并分享给我的朋友">收藏</a> </cite>
</h1>
<div>
<script type="text/javascript">
document.body.oncopy = function() {
if (window.clipboardData) {
setTimeout(function() {
var text = clipboardData.getData("text");
if (text && text.length > 300) {
text = text + ""r"n"n本文来自CSDN博客，转载请标明出处：" + location.href;
clipboardData.setData("text", text);
}
}, 100);
}
}
</script>
<script type="text/javascript">                        function StorePage() { d = document; t = d.selection ? (d.selection.type != 'None' ? d.selection.createRange().text : '') : (d.getSelection ? d.getSelection() : ''); void (keyit = window.open('http://www.365key.com/storeit.aspx?t=' + escape(d.title) + '&u=' + escape(d.location.href) + '&c=' + escape(t), 'keyit', 'scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes')); keyit.focus(); }</script>
<p>Spring提供了两个这样的数据源（都位于org.springframework.jdbc.datasource程序包里）：<br />
DriverManagerDataSource：在每个连接请求时都新建一个连接。与DBCP的BasicDataSource不同，DriverManagerDataSource提供的连接没有进行池管理。<br />
SingleConnectionDataSource：在每个连接请求时都返回同一个连接。虽然它不同严格意义上的池管理数据源，但我们可以把它看作只有一个连接的池。<br />
对两个数据源的配置都类似于配置DBCP的BasicDataSource<br />
区别在于由于DriverManagerDataSource和SingleConnectionDataSource都没有提供连接池，所以在此没有设置池配置属性。<br />
虽然这两个数据源都对于小程序来说是很不错的，而且还在不断发展，但把它们用于生产程序还是需要认真考虑的。</p>
<p>SingleConnectionDataSource只使用一个数据库连接，所以不适合用于多线程程序。而
DriverMangerDataSource虽然能够支持多线程，但它会在每次连接请求时都新建一个连接，这是以性能为代价的。由于这些限制，我们强烈
建议应该使用数据源池。</p>
<p>在通过数据源与数据库建立连接之后，我们就要实际访问数据库了，而最基本的方式就是使用JDBC，现在我们就来看一看Spring如何让使用简单的JDBC更加简便。<br />
&nbsp;Spring在第三方依赖包中包含了两个数据源的实现类包，其一是Apache的DBCP，其二是 C3P0。可以在Spring配置文件中利用这两者中任何一个配置数据源。</p>
<p>DBCP数据源 <br />
&nbsp;&nbsp;&nbsp;&nbsp; DBCP 类包位于
/lib/jakarta-commons/commons-dbcp.jar，DBCP是一个依赖 Jakarta commons-
pool对象池机制的数据库连接池，所以在类路径下还必须包括/lib/jakarta-
commons/commons-pool.jar。下面是使 用DBCP配置MySql数据源的配置片断：</p>
<p>xml 代码<br />
&lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; destroy-method="close"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="driverClassName" value="com.mysql.jdbc.Driver" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="url" value="jdbc:mysql://localhost:3309/sampledb" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="username" value="root" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="password" value="1234" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
bean&gt;&nbsp;&nbsp; </p>
<p>BasicDataSource提供了close()方法关闭数据源，所以必须设定destroy-method=&#8221;close&#8221;属性， 以便Spring容器关闭时，数据源能够正常关闭。除以上必须的数据源属性外，还有一些常用的属性： <br />
&nbsp;&nbsp;&nbsp;&nbsp; defaultAutoCommit：设置从数据源中返回的连接是否采用自动提交机制，默认值为 true； <br />
&nbsp;&nbsp;&nbsp;&nbsp; defaultReadOnly：设置数据源是否仅能执行只读操作， 默认值为 false； <br />
&nbsp;&nbsp;&nbsp;&nbsp; maxActive：最大连接数据库连接数，设置为0时，表示没有限制； <br />
&nbsp;&nbsp;&nbsp;&nbsp; maxIdle：最大等待连接中的数量，设置为0时，表示没有限制； <br />
&nbsp;&nbsp;&nbsp;&nbsp; maxWait：最大等待秒数，单位为毫秒， 超过时间会报出错误信息； <br />
&nbsp;&nbsp;&nbsp;&nbsp; validationQuery：用于验证连接是否成功的查询SQL语句，SQL语句必须至少要返回一行数据， 如你可以简单地设置为：&#8220;select count(*) from user&#8221;； <br />
&nbsp;&nbsp;&nbsp;&nbsp; removeAbandoned：是否自我中断，默认是 false ； <br />
&nbsp;&nbsp;&nbsp;&nbsp; removeAbandonedTimeout：几秒后数据连接会自动断开，在removeAbandoned为true，提供该值； <br />
&nbsp;&nbsp;&nbsp;&nbsp; logAbandoned：是否记录中断事件， 默认为 false； </p>
<p>C3P0数据源 <br />
&nbsp;&nbsp;&nbsp;&nbsp; C3P0
是一个开放源代码的JDBC数据源实现项目，它在lib目录中与Hibernate一起发布，实现了JDBC3和JDBC2扩展规范说明的
Connection 和Statement 池。C3P0类包位于/lib/c3p0/c3p0-0.9.0.4.jar。下面是使用C3P0配置一
个 oracle数据源：</p>
<p>xml 代码<br />
&lt;bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; destroy-method="close"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="driverClass" value=" oracle.jdbc.driver.OracleDriver "/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="jdbcUrl" value=" jdbc:oracle:thin:@localhost:1521:ora9i "/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="user" value="admin"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="password" value="1234"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
bean&gt;&nbsp;&nbsp; </p>
<p>ComboPooledDataSource和BasicDataSource一样提供了一个用于关闭数据源的close()方法，这样我们就可以保证Spring容器关闭时数据源能够成功释放。 <br />
&nbsp;&nbsp;&nbsp;&nbsp; C3P0拥有比DBCP更丰富的配置属性，通过这些属性，可以对数据源进行各种有效的控制： <br />
&nbsp;&nbsp;&nbsp;&nbsp; acquireIncrement：当连接池中的连接用完时，C3P0一次性创建新连接的数目； <br />
&nbsp;&nbsp;&nbsp;&nbsp; acquireRetryAttempts：定义在从数据库获取新连接失败后重复尝试获取的次数，默认为30； <br />
&nbsp;&nbsp;&nbsp;&nbsp; acquireRetryDelay：两次连接中间隔时间，单位毫秒，默认为1000； <br />
&nbsp;&nbsp;&nbsp;&nbsp; autoCommitOnClose：连接关闭时默认将所有未提交的操作回滚。默认为false； <br />
&nbsp;&nbsp;&nbsp;&nbsp;
automaticTestTable：
C3P0将建一张名为Test的空表，并使用其自带的查询语句进行测试。如果定义了这个参数，那么属性preferredTestQuery将被忽略。
你 不能在这张Test表上进行任何操作，它将中为C3P0测试所用，默认为null； <br />
&nbsp;&nbsp;&nbsp;&nbsp;
breakAfterAcquireFailure： 获取连接失败将会引起所有等待获取连接的线程抛出异常。但是数据源仍有效保留，并在下次调&nbsp;&nbsp;&nbsp;
用getConnection()的时候继续尝试获取连 接。如果设为true，那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。默认为
false； <br />
&nbsp;&nbsp;&nbsp;&nbsp; checkoutTimeout：当连接池用完时客户端调用getConnection()后等待获取新连接的时间，超时后将抛出SQLException，如设为0则无限期等待。单位毫秒，默认为0； <br />
&nbsp;&nbsp;&nbsp;&nbsp;
connectionTesterClassName：
通过实现ConnectionTester或QueryConnectionTester的类来测试连接，类名需设置为全限定名。默认为
com.mchange.v2.C3P0.impl.DefaultConnectionTester； <br />
&nbsp;&nbsp;&nbsp;&nbsp; idleConnectionTestPeriod：隔多少秒检查所有连接池中的空闲连接，默认为0表示不检查； <br />
&nbsp;&nbsp;&nbsp;&nbsp; initialPoolSize：初始化时创建的连接数，应在minPoolSize与maxPoolSize之间取值。默认为3； <br />
&nbsp;&nbsp;&nbsp;&nbsp; maxIdleTime：最大空闲时间，超过空闲时间的连接将被丢弃。为0或负数则永不丢弃。默认为0； <br />
&nbsp;&nbsp;&nbsp;&nbsp; maxPoolSize：连接池中保留的最大连接数。默认为15； <br />
&nbsp;&nbsp;&nbsp;&nbsp;
maxStatements：
JDBC的标准参数，用以控制数据源内加载的PreparedStatement数量。但由于预缓存的Statement属
于单个Connection 而不是整个连接池。所以设置这个参数需要考虑到多方面的因素，如果maxStatements与
maxStatementsPerConnection 均为0，则缓存被关闭。默认为0； <br />
&nbsp;&nbsp;&nbsp;&nbsp; maxStatementsPerConnection：连接池内单个连接所拥有的最大缓存Statement数。默认为0； <br />
&nbsp;&nbsp;&nbsp;&nbsp; numHelperThreads：C3P0是异步操作的，缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能，通过多线程实现多个操作同时被执行。默认为3； <br />
&nbsp;&nbsp;&nbsp;&nbsp; preferredTestQuery：定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个参数能显著提高测试速度。测试的表必须在初始数据源的时候就存在。默认为null； <br />
&nbsp;&nbsp;&nbsp;&nbsp; propertyCycle： 用户修改系统配置参数执行前最多等待的秒数。默认为300； <br />
&nbsp;&nbsp;&nbsp;&nbsp;
testConnectionOnCheckout：
因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的时候都 将校验其有效性。建议使用
idleConnectionTestPeriod或automaticTestTable <br />
等方法来提升连接测试的性能。默认为false； <br />
&nbsp;&nbsp;&nbsp;&nbsp; testConnectionOnCheckin：如果设为true那么在取得连接的同时将校验连接的有效性。默认为false。 </p>
<p>读配置文件的方式引用属性： </p>
<p>&lt;bean id="propertyConfigurer"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="location" value="/WEB-INF/jdbc.properties"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
bean&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; destroy-method="close"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="url" value="${jdbc.url}" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="username" value="${jdbc.username}" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="password" value="${jdbc.password}" /&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
bean&gt;&nbsp;&nbsp;&nbsp; </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp; 在jdbc.properties属性文件中定义属性值： <br />
&nbsp;&nbsp;&nbsp;&nbsp; jdbc.driverClassName= com.mysql.jdbc.Driver <br />
&nbsp;&nbsp;&nbsp;&nbsp; jdbc.url= jdbc:mysql://localhost:3309/sampledb <br />
&nbsp;&nbsp;&nbsp;&nbsp; jdbc.username=root <br />
&nbsp;&nbsp;&nbsp;&nbsp; jdbc.password=1234 <br />
&nbsp;&nbsp;&nbsp;&nbsp; 提示 经常有开发者在${xxx}的前后不小心键入一些空格，这些空格字符将和变量合并后作为属性的值。如： 的属性配置项，在前后都有空格，被解析后，username的值为&#8220; 1234 &#8221;，这将造成最终的错误，因此需要特别小心。</p>
<p>获取JNDI数据源 <br />
&nbsp;&nbsp;&nbsp;&nbsp;
如果应用配置在高性能的应用服务器（如WebLogic或Websphere等）上，我们可能更希望使用应用服务器本身提供的数据源。应用服务器的数据源
使用JNDI开放调用者使用，Spring为此专门提供引用JNDI资源的JndiObjectFactoryBean类。下面是一个简单的配置：</p>
<p>xml 代码<br />
&lt;bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="jndiName" value="java:comp/env/jdbc/bbt"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
bean&gt;&nbsp;&nbsp; </p>
<p>通过jndiName指定引用的JNDI数据源名称。 <br />
&nbsp;&nbsp;&nbsp;&nbsp; Spring 2.0为获取J2EE资源提供了一个jee命名空间，通过jee命名空间，可以有效地简化J2EE资源的引用。下面是使用jee命名空间引用JNDI数据源的配置： </p>
<p>xml 代码<br />
&lt;beans xmlns=http://www.springframework.org/schema/beans&nbsp;&nbsp;&nbsp;&nbsp; <br />
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&nbsp;&nbsp;&nbsp;&nbsp; <br />
xmlns:jee=http://www.springframework.org/schema/jee&nbsp;&nbsp;&nbsp;&nbsp; <br />
xsi:schemaLocation="<a href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
<a href="http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">http://www.springframework.org/schema/beans/spring-beans-2.0.xsd</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
<a href="http://www.springframework.org/schema/jee">http://www.springframework.org/schema/jee</a>&nbsp;&nbsp;&nbsp;&nbsp; <br />
<a href="http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">http://www.springframework.org/schema/jee/spring-jee-2.0.xsd</a>"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&lt;jee:jndi-lookup id="dataSource" jndi-name=" java:comp/env/jdbc/bbt"/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
beans&gt;&nbsp;&nbsp; </p>
<p>Spring的数据源实现类 <br />
&nbsp;&nbsp;&nbsp;&nbsp; Spring
本身也提供了一个简单的数据源实现类DriverManagerDataSource ，它位于
org.springframework.jdbc.datasource包中。这个类实现了javax.sql.DataSource接口，但
它并没
有提供池化连接的机制，每次调用getConnection()获取新连接时，只是简单地创建一个新的连接。因此，这个数据源类比较适合在单元测试
或简 单的独立应用中使用，因为它不需要额外的依赖类。 <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 下面，我们来看一下DriverManagerDataSource的简单使用：当然，我们也可以通过配置的方式直接使用DriverManagerDataSource。</p>
<p>java 代码<br />
DriverManagerDataSource ds = new DriverManagerDataSource ();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
ds.setDriverClassName("com.mysql.jdbc.Driver");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
ds.setUrl("jdbc:mysql://localhost:3309/sampledb");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
ds.setUsername("root");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
ds.setPassword("1234");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
Connection actualCon = ds.getConnection();&nbsp;&nbsp; </p>
<p>小结 </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;
不管采用何种持久化技术，都需要定义数据源。Spring附带了两个数据源的实现类包，你可以自行选择进行定义。在实际部署时，我们可能会直接采用应用服
务器本身提供的数据源，这时，则可以通过JndiObjectFactoryBean或jee命名空间引用JNDI中的数据源。 </p>
<p>DBCP与C3PO配置的区别：</p>
<p>C3PO ：</p>
<p>xml 代码</p>
<p>&lt;bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="driverClass"&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;oracle.jdbc.driver.OracleDrivervalue&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; property&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="jdbcUrl"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;jdbc:oracle:thin:@10.10.10.6:1521:DataBaseNamevalue&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; property&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="user"&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;testAdminvalue&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; property&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="password"&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;123456value&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; property&gt;&nbsp;&nbsp; <br />
bean&gt;&nbsp;&nbsp; </p>
<p>DBCP：</p>
<p>xml 代码<br />
&lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="driverClassName"&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;oracle.jdbc.driver.OracleDrivervalue&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; property&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="url"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;jdbc:oracle:thin:@10.10.10.6:1521:DataBaseNamevalue&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; property&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="username"&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;testAdminvalue&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; property&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="password"&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;123456value&gt;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp; property&gt;&nbsp;&nbsp; <br />
bean&gt;</p>
</div>
<br />
</div>
<img src ="http://www.blogjava.net/sealyu/aggbug/311728.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2010-02-02 22:04 <a href="http://www.blogjava.net/sealyu/archive/2010/02/02/311728.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>SQL 中 with as 用法(转)</title><link>http://www.blogjava.net/sealyu/archive/2009/11/12/302068.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Thu, 12 Nov 2009 03:12:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2009/11/12/302068.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/302068.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2009/11/12/302068.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/302068.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/302068.html</trackback:ping><description><![CDATA[<p><a href="javascript:;" onclick="javascript:tagshow(event, 'with');" target="_self"><u><strong>with</strong></u></a><br />
sql1 as (select to_char(a) s_name from test_tempa),<br />
<span style="display: none;">R
]F5^5"KFW0n
B0</span>sql2 as (select to_char(b) s_name from test_tempb where not exists (select s_name from sql1 where rownum=1))<br />
select * from sql1<span style="display: none;">ITPUB个人空间2g
N*`O3y2eB
Q6}</span><br />
union all<br />
select * from sql2<br />
union all<br />
select 'no records' from dual<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; where not exists (select s_name from sql1 where rownum=1)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; and not exists (select s_name from sql2 where rownum=1);</p>
<p>再举个简单的例子</p>
<p>with a as (select * from test)</p>
<p>select * from a;<br />
</p>
<p>其实就是把一大堆重复用到的SQL语句放在with as 里面，取一个别名，后面的查询就可以用它</p>
<p>这样对于大批量的SQL语句起到一个优化的作用，而且清楚明了</p>
<p><br />
</p>
这是搜索到的英文文档资料(说得比较全,但是本人英文特菜,还没具体了解到,希望各高手具体谈谈这个with <br />
as 的好处)<br />
<br />
<strong>
<div><strong><font size="6"><font color="#000000" size="5">About Oracle WITH clause </font></font></strong></div>
</strong>
<div>Starting in Oracle9i release 2 we see an incorporation of the SQL-99 &#8220;WITH clause&#8221;, a tool for materializing subqueries to save Oracle from having to re-compute them multiple times.<br />
<br />
The SQL &#8220;WITH
clause&#8221; is very similar to the use of Global temporary tables (GTT), a
technique that is often used to improve query speed for complex
subqueries. Here are some important notes about the Oracle &#8220;WITH clause&#8221;:<br />
<br />
&nbsp;&nbsp; &#8226; The SQL &#8220;WITH clause&#8221; only works on Oracle 9i release 2 and beyond.<br />
&nbsp;&nbsp; &#8226; Formally, the &#8220;WITH clause&#8221; is called subquery factoring<br />
&nbsp;&nbsp; &#8226; The SQL &#8220;WITH clause&#8221; is used when a subquery is executed multiple times<br />
&nbsp;&nbsp; &#8226; Also useful for recursive queries (SQL-99, but not Oracle SQL)<br />
<br />
To keep it simple, the following example only references the
aggregations once, where the SQL &#8220;WITH clause&#8221; is normally used when an aggregation is referenced multiple times in a query. </div>
<div>We can also use the SQL-99 &#8220;WITH clause&#8221; instead of temporary tables. The Oracle SQL &#8220;WITH
clause&#8221; will compute the aggregation once, give it a name, and allow us
to reference it (maybe multiple times), later in the query.<br />
<br />
The SQL-99 &#8220;WITH clause&#8221; is very confusing at first because the SQL statement does not begin with the word SELECT. Instead, we use the &#8220;WITH clause&#8221; to start our SQL query, defining the aggregations, which can then be named in the main query as if they were &#8220;real&#8221; tables:<br />
<br />
<font size="2">WITH <br />
subquery_name<br />
AS<br />
(the aggregation SQL statement)<br />
SELECT<br />
(query naming subquery_name);</font><br />
<br />
Retuning to our oversimplified example, let&#8217;s replace the temporary tables with the SQL &#8220;WITH&nbsp; clause&#8221;:<br />
<br />
<font size="2">WITH<br />
sum_sales AS <br />
&nbsp; select /*+ materialize */ <br />
&nbsp;&nbsp;&nbsp; sum(quantity) all_sales from stores<br />
number_stores AS <br />
&nbsp; select /*+ materialize */ <br />
&nbsp;&nbsp;&nbsp; count(*) nbr_stores from stores<br />
sales_by_store AS<br />
&nbsp; select /*+ materialize */ <br />
&nbsp; store_name, sum(quantity) store_sales from <br />
&nbsp; store natural join sales<br />
SELECT<br />
&nbsp;&nbsp; store_name<br />
FROM<br />
&nbsp;&nbsp; store,<br />
&nbsp;&nbsp; sum_sales,<br />
&nbsp;&nbsp; number_stores,<br />
&nbsp;&nbsp; sales_by_store<br />
where<br />
&nbsp;&nbsp; store_sales &gt; (all_sales / nbr_stores)<br />
;</font><br />
<br />
Note the use of the Oracle undocumented &#8220;materialize&#8221; hint in the &#8220;WITH clause&#8221;. The Oracle materialize hint is used to ensure that the Oracle cost-based optimizer materializes the temporary tables that are created inside the &#8220;WITH&#8221; clause. This is not necessary in Oracle10g, but it helps ensure that the tables are only created one time.<br />
<br />
It should be noted that the &#8220;WITH clause&#8221; does not yet fully-functional within Oracle SQL and it does not yet support the use of &#8220;WITH clause&#8221; replacement for &#8220;CONNECT BY&#8221; when performing recursive queries.<br />
<br />
To see how the &#8220;WITH clause&#8221; is used in ANSI SQL-99 syntax, here is an excerpt from Jonathan Gennick&#8217;s great work &#8220;Understanding the WITH Clause&#8221; showing the use of the SQL-99 &#8220;WITH clause&#8221; to traverse a recursive bill-of-materials hierarchy</div>
<p>The SQL-99 &#8220;WITH clause&#8221; is very confusing at first because the SQL statement does not begin with the word SELECT. Instead, we use the &#8220;WITH clause&#8221; to start our SQL query, defining the aggregations, which can then be named in the main query as if they were &#8220;real&#8221; tables:<br />
<br />
<font size="1">WITH <br />
subquery_name<br />
AS<br />
(the aggregation SQL statement)<br />
SELECT<br />
(query naming subquery_name);</font> </p>
<br />
Retuning to our oversimplified example, let&#8217;s replace the temporary tables with the SQL &#8220;WITH&#8221; clause&#8221;:<br />
<br />
另一个例子:<br />
with tempDeptName(deptName) as <br />
(<br />
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;select <br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; dept_name as deptName<br />
&nbsp;&nbsp;&nbsp; &nbsp;from <br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; bas_dept as dept,tpp_materialmuster as muster<br />
&nbsp;&nbsp;&nbsp; &nbsp;where <br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; dept.DEPT_ID = muster.NEEDUNIT<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp; &nbsp;union all<br />
&nbsp;&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp;&nbsp; &nbsp;select <br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; corp_name as deptName<br />
&nbsp;&nbsp;&nbsp; &nbsp;from<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; bas_corp as corp,tpp_materialmuster as muster<br />
&nbsp;&nbsp;&nbsp; &nbsp;where<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; corp.corp_id = muster.NEEDUNIT<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <br />
),<br />
tempProjInfo(projName, projCode) as<br />
(<br />
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;select <br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; etfprojName as projName,<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; etfprojCode as projCode<br />
&nbsp;&nbsp;&nbsp; &nbsp;from <br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; tbi_etfproj as etf, tpp_materialMuster as muster<br />
&nbsp;&nbsp;&nbsp; &nbsp;where<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; etf.etfprojid = muster.projid<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp; &nbsp;union all<br />
&nbsp;&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp;&nbsp; &nbsp;select <br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; etmprojName as projName,<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; etmprojCode as projCode<br />
&nbsp;&nbsp;&nbsp; &nbsp;from<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; tbi_etmproj as etm, tpp_materialMuster as muster<br />
&nbsp;&nbsp;&nbsp; &nbsp;where<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; etm.etmprojId = muster.projid<br />
)<br />
<br />
select<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; deptname,<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp; projname,<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp; projcode<br />
&nbsp;&nbsp;&nbsp; &nbsp; from &nbsp;&nbsp;&nbsp; tpp_materialmuster as muster,tempDeptName,tempProjInfo
<br />
<img src ="http://www.blogjava.net/sealyu/aggbug/302068.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2009-11-12 11:12 <a href="http://www.blogjava.net/sealyu/archive/2009/11/12/302068.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>How to convert from string to datetime in sql server?</title><link>http://www.blogjava.net/sealyu/archive/2009/11/05/301216.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Thu, 05 Nov 2009 01:59:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2009/11/05/301216.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/301216.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2009/11/05/301216.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/301216.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/301216.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: Execute the followingT-SQL scripts in Microsoft SQL Server Manangement Studio Query Editorto demonstrate T-SQL convert and cast functions in transforming stringdate, string time &amp; string dat...&nbsp;&nbsp;<a href='http://www.blogjava.net/sealyu/archive/2009/11/05/301216.html'>阅读全文</a><img src ="http://www.blogjava.net/sealyu/aggbug/301216.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2009-11-05 09:59 <a href="http://www.blogjava.net/sealyu/archive/2009/11/05/301216.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>标注枚举类型@Enumerated（转）</title><link>http://www.blogjava.net/sealyu/archive/2009/06/30/284749.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Tue, 30 Jun 2009 05:18:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2009/06/30/284749.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/284749.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2009/06/30/284749.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/284749.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/284749.html</trackback:ping><description><![CDATA[<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">实体</span><font face="Times New Roman">Entity</font><span style="font-family: 宋体;">中通过</span><font face="Times New Roman">@Enumerated</font><span style="font-family: 宋体;">标注枚举类型，例如将</span><font face="Times New Roman">CustomerEO</font><span style="font-family: 宋体;">实体中增加一个</span><font face="Times New Roman">CustomerType</font><span style="font-family: 宋体;">类型的枚举型属性，标注实体后的代码如下所示。</span></font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">@Entity</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">@Table(name = "customer")</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">public class CustomerEO implements java.io.Serializable {</font></p>
<p style="margin: 0cm 0cm 0pt auto; text-indent: 21pt;"><span style="font-family: 黑体;"><font style="background-color: #e0e0e0;">&#8230;&#8230;</font></span></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private CustomerType type;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @Enumerated(EnumType.STRING)</font></strong></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public CustomerType getType() {</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return type;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void setType(CustomerType type) {</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.type = type;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public enum CustomerType {</font></strong></p>
<p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; COMPETITOR, INVESTOR, PARTNER, VENDER</font></strong></p>
<p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</font></strong></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">}</font></p>
<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">在实体中虽然标注成枚举类型，但当实体持久化后，表中所对应的值仍旧是基本的数据类型，以上代码创建表的</span><font face="Times New Roman">SQL</font><span style="font-family: 宋体;">语句是：</span></font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">CREATE TABLE customer (</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; id int(20) NOT NULL auto_increment,</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name varchar(255),</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; type varchar(255),</font></strong></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PRIMARY KEY (id)</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">)</font></p>
<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><span style="font-family: 宋体;"><font size="3">使用枚举类型后，在创建实体时便可以直接引用枚举类型，例如以下代码所示。</font></span></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">CustomerEO customer = new CustomerEO();</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">customer.setName("Janet2");</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">customer.setType(<strong>CustomerType.PARTNER</strong>);</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">entityManager.persist(customer);</font></p>
<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">在使用</span><font face="Times New Roman">@Enumerated</font><span style="font-family: 宋体;">注释时，需要注意以下几个问题：</span></font></p>
<p style="margin: 0cm 0cm 0pt 21pt;"><span style="font-family: Wingdings;"><font size="3">l</font><span style="font-family: &quot;Times New Roman&quot;; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><font size="3"><span style="font-family: 宋体;">因为枚举类型的有名称和值两个属性，所以在持久化时可以选择持久化名称或是持久化值。通过</span><font face="Times New Roman">EnumType</font><span style="font-family: 宋体;">来定义，它有两个值如下所示。</span></font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">public enum EnumType {</font></p>
<p style="margin: 0cm 0cm 0pt auto; text-indent: 21pt;"><font style="background-color: #e0e0e0;">ORDINAL,</font></p>
<p style="margin: 0cm 0cm 0pt auto; text-indent: 21pt;"><font style="background-color: #e0e0e0;">STRING</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">}</font></p>
<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">表示持久化的为枚举类型的值，</span><font face="Times New Roman">STRING</font><span style="font-family: 宋体;">表示持久化的为枚举类型的名称。默认为</span><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">，持久化值。例如以上示例中标注的为</span><font face="Times New Roman">STRING</font><span style="font-family: 宋体;">，这样持久化实体后，数据库中保存的是枚举类型的名称，如图</span><span style="font-family: 宋体;">所示。</span></font></p>
<p style="margin: 0cm 0cm 12pt;" align="center"><span style="font-family: 宋体;"><img alt="" src="http://p.blog.csdn.net/images/p_blog_csdn_net/EJB_JPA/5.5.jpg" /></span></p>
<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">若此时改成</span><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">，代码如下：</span></font></p>
<p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @Enumerated(EnumType.ORDINAL)</font></strong></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public CustomerType getType() {</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return type;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</font></p>
<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">则同样持久化的实体后，数据库保存的结果如图</span><span style="font-family: 宋体;">所示。</span></font></p>
<p style="margin: 0cm 0cm 12pt;" align="center"><span style="font-family: 宋体;"><img alt="" src="http://p.blog.csdn.net/images/p_blog_csdn_net/EJB_JPA/5.6.jpg" /></span></p>
<p style="margin: 0cm 0cm 0pt 21pt;"><span style="font-family: Wingdings;"><font size="3">l</font><span style="font-family: &quot;Times New Roman&quot;; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><font size="3"><span style="font-family: 宋体;">如何选择</span><font face="Times New Roman">STRING</font><span style="font-family: 宋体;">和</span><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">：</span></font></p>
<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">如果使用</span><font face="Times New Roman">STRING</font><span style="font-family: 宋体;">保存，虽然从数据库中查询数据时非常直观，能够清楚的看出该类型代表意义，但这样也会带来其他的问题。若此时枚举类型的定义改变，例如上例中的枚举类型名称改为：</span></font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public enum CustomerType {</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CUST_COMPETITOR, INVESTOR, PARTNER, VENDER</font></strong></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</font></p>
<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">则此时数据库中保存的&#8220;</span><font face="Times New Roman">COMPETITOR</font><span style="font-family: 宋体;">&#8221;的值将不能转化为枚举类型</span><font face="Times New Roman">CustomerType</font><span style="font-family: 宋体;">中的&#8220;</span><font face="Times New Roman">CUST_COMPETITOR</font><span style="font-family: 宋体;">&#8221;的值。但若使用</span><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">则不会带来这种问题。所以建议使用</span><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">类型来持久化枚举类型。</span></font></p>
<p style="margin: 0cm 0cm 0pt 21pt;"><span style="font-family: Wingdings;"><font size="3">l</font><span style="font-family: &quot;Times New Roman&quot;; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><font size="3"><span style="font-family: 宋体;">枚举类型的定义位置，实体外部</span><font face="Times New Roman">VS</font><span style="font-family: 宋体;">实体内部。</span></font></p>
<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">上例中</span><font face="Times New Roman">CustomerType</font><span style="font-family: 宋体;">枚举类型定义在</span><font face="Times New Roman">CustomerEO</font><span style="font-family: 宋体;">实体内部，这是因为只有</span><font face="Times New Roman">CustomerEO</font><span style="font-family: 宋体;">这个实体会使用</span><font face="Times New Roman">CustomerType</font><span style="font-family: 宋体;">类型，其他的实体不会使用该类型。该类型与这个实体关系紧密联系。</span></font></p>
<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">但若此时多个实体公用一个枚举类型时，则可以将枚举类型单独定义，定义在实体的外部。有这样一个枚举类型</span><font face="Times New Roman">BusinessLine</font><span style="font-family: 宋体;">，它定义在实体外部，代码如下：</span></font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">public enum BusinessLine {</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; REAL_ESTATE,FINANCE, NON_PROFIT</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">}</font></p>
<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">例如</span><font face="Times New Roman">CustomerEO</font><span style="font-family: 宋体;">实体增加一个</span><font face="Times New Roman">BusinessLine</font><span style="font-family: 宋体;">的枚举类型，代码如下所示。</span></font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">@Entity</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">@Table(name = "customer")</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">public class CustomerEO implements java.io.Serializable {</font></p>
<p style="margin: 0cm 0cm 0pt auto; text-indent: 21pt;"><span style="font-family: 黑体;"><font style="background-color: #e0e0e0;">&#8230;&#8230;</font></span></p>
<p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private BusinessLine businessLine;</font></strong></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @Enumerated(EnumType.STRING)</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public BusinessLine getBusinessLine() {</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return businessLine;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void setBusinessLine(BusinessLine businessLine) {</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.businessLine = businessLine;</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</font></p>
<p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">}</font></p>
<img src ="http://www.blogjava.net/sealyu/aggbug/284749.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2009-06-30 13:18 <a href="http://www.blogjava.net/sealyu/archive/2009/06/30/284749.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title> JAVA连接池(转)</title><link>http://www.blogjava.net/sealyu/archive/2009/03/13/259574.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Fri, 13 Mar 2009 08:58:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2009/03/13/259574.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/259574.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2009/03/13/259574.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/259574.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/259574.html</trackback:ping><description><![CDATA[<p>package com.xinnuo.jdbc;</p>
<p>import java.io.*;<br />
import java.sql.*;<br />
import java.util.*;<br />
import java.util.Date;</p>
<p>&nbsp;/*<br />
&nbsp; * 该类只能创建一个实例，其它对象能够调用其静态方法（也称为类方法）获得该唯一实例的引用。<br />
&nbsp; * DBConnectionManager类的建构函数是私有的，这是为了避免其它对象创建该类的实例.<br />
&nbsp; * DBConnectionManager类的客户程序可以调用getInstance()方法获得对该类唯一实例的引用。<br />
&nbsp; * 类的唯一实例在getInstance()方法第一次被调用期间创建，此后其引用就一直保存在静态变量<br />
&nbsp; * instance中。每次调用getInstance()都增加一个DBConnectionManager的客户程序计数。<br />
&nbsp; * 即，该计数代表引用DBConnectionManager唯一实例的客户程序总数，它将被用于控制连接池的<br />
&nbsp; * 关闭操作。 该类实例的初始化工作私有方法init()完成。其中 getResourceAsStream()方法<br />
&nbsp; * 用于定位并打开外部文件。外部文件的定位方法依赖于类装载器的实现。标准的本地类装载器查找操<br />
&nbsp; * 作总是开始于类文件所在路径，也能够搜索CLASSPATH中声明的路径。db.properties是一个属性<br />
&nbsp; * 文件，它包含定义连接池的键-值对。可供定义的公用属性如下： <br />
&nbsp; * &nbsp;&nbsp;drivers 以空格分隔的JDBC驱动程序类列表"" <br />
&nbsp; * &nbsp;&nbsp;logfile 日志文件的绝对路径 <br />
&nbsp; *&nbsp;&nbsp;其它的属性和特定连接池相关，其属性名字前应加上连接池名字： <br />
&nbsp; *&nbsp;&nbsp;&lt; poolname&gt;.url 数据库的 JDBC URL <br />
&nbsp; *&nbsp;&nbsp;&lt; poolname&gt;.maxconn 允许建立的最大连接数，0表示没有限制 <br />
&nbsp; *&nbsp;&nbsp;&lt; poolname&gt;.user 用于该连接池的数据库帐号 <br />
&nbsp; *&nbsp;&nbsp;&lt; poolname&gt;.password 相应的密码""<br />
&nbsp; *&nbsp;其中url属性是必需的，而其它属性则是可选的。数据库帐号和密码必须合法。用于Windows平台的<br />
&nbsp; *&nbsp;db.properties文件示例如下：<br />
&nbsp; *&nbsp;&nbsp;drivers=com.microsoft.jdbc.sqlserver.SQLServerDriver<br />
&nbsp; *&nbsp;&nbsp;logfile=D:""log.txt<br />
&nbsp; *&nbsp;&nbsp;access.maxconn=20<br />
&nbsp; *&nbsp;&nbsp;access.url=jdbc:microsoft:sqlserver://localhost:1433;databasename=web<br />
&nbsp; *&nbsp;&nbsp;access.user=sa<br />
&nbsp; *&nbsp;&nbsp;access.password=sa&nbsp;<br />
&nbsp; *&nbsp;注意在Windows路径中的反斜杠必须输入2个，这是由于属性文件中的反斜杠同时也是一个转义字符。<br />
&nbsp; *&nbsp;init()方法在创建属性对象并读取db.properties文件之后，就开始检查logfile属性。如果属<br />
&nbsp; *&nbsp;性文件中没有指定日志文件，则默认为当前目录下的DBConnectionManager.log文件。如日志文<br />
&nbsp; *&nbsp;件无法使用，则向System.err输出日志记录。装载和注册所有在drivers属性中指定的JDBC驱动<br />
&nbsp; *&nbsp;程序loadDrivers()方法实现。该方法先用StringTokenizer将drivers属性值分割为对应于驱<br />
&nbsp; *&nbsp;动程序名称的字符串，然后依次装载这些类并创建其实例，最后在DriverManager中注册该实例并把<br />
&nbsp; *&nbsp;它加入到一个私有的向量drivers。向量drivers将用于关闭服务时从DriverManager取消所有<br />
&nbsp; *&nbsp;JDBC 驱动程序的注册。init()方法的最后一个任务是调用私有方法createPools()创建连接池对<br />
&nbsp; *&nbsp;象。createPools()方法先创建所有属性名字的枚举对象（即Enumeration对象，该对象可以想象<br />
&nbsp; *&nbsp;为一个元素系列，逐次调用其nextElement()方法将顺序返回各元素），然后在其中搜索名字以&#8220;.url&#8221;<br />
&nbsp; *&nbsp;结尾的属性。对于每一个符合条件的属性，先提取其连接池名字部分，进而读取所有属于该连接池的属性，<br />
&nbsp; *&nbsp;最后创建连接池对象并把它保存在实例变量pools中。散列表（Hashtable类 ）pools实现连接池名字<br />
&nbsp; *&nbsp;到连接池对象之间的映射，此处以连接池名字为键，连接池对象为值。 为便于客户程序从指定连接池获<br />
&nbsp; *&nbsp;得可用连接或将连接返回给连接池，类DBConnectionManager提供了方法getConnection()和<br />
&nbsp; *&nbsp;freeConnection()。所有这些方法都要求在参数中指定连接池名字，具体的连接获取或返回操作则调<br />
&nbsp; *&nbsp;用对应的连接池对象完成。为实现连接池的安全关闭，DBConnectionManager提供了方法release()。<br />
&nbsp; *&nbsp;在上面我们已经提到，所有DBConnectionManager的客户程序都应该调用静态方法getInstance()<br />
&nbsp; *&nbsp;以获得该管理器的引用，此调用将增加客户程序计数。客户程序在关闭时调用release()可以递减该计数。<br />
&nbsp; *&nbsp;当最后一个客户程序调用release()，递减后的引用计数为0，就可以调用各个连接池的release()方法<br />
&nbsp; *&nbsp;关闭所有连接了。管理类release()方法最后的任务是撤销所有JDBC驱动程序的注册。<br />
&nbsp; */</p>
<p>/**<br />
&nbsp;* 管理类DBConnectionManager支持对一个或多个由属性文件定义的数据库连接<br />
&nbsp;* 池的访问.客户程序可以调用getInstance()方法访问本类的唯一实例.<br />
&nbsp;*/<br />
public class DBConnectionManager {<br />
&nbsp;static private DBConnectionManager instance; // 唯一实例</p>
<p>&nbsp;static private int clients;</p>
<p>&nbsp;private Vector drivers = new Vector();</p>
<p>&nbsp;private PrintWriter log;</p>
<p>&nbsp;private Hashtable pools = new Hashtable();</p>
<p>&nbsp;/**<br />
&nbsp; * 返回唯一实例.如果是第一次调用此方法,则创建实例<br />
&nbsp; * @return DBConnectionManager 唯一实例<br />
&nbsp; */<br />
&nbsp;static synchronized public DBConnectionManager getInstance() {<br />
&nbsp;&nbsp;if (instance == null) {<br />
&nbsp;&nbsp;&nbsp;instance = new DBConnectionManager();<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;clients++;<br />
&nbsp;&nbsp;return instance;<br />
&nbsp;}</p>
<p>&nbsp;/**<br />
&nbsp; * 建构函数私有以防止其它对象创建本类实例<br />
&nbsp; */<br />
&nbsp;private DBConnectionManager() {<br />
&nbsp;&nbsp;init();<br />
&nbsp;}</p>
<p>&nbsp;/**<br />
&nbsp; * * 将连接对象返回给由名字指定的连接池<br />
&nbsp; * @param name在属性文件中定义的连接池名字<br />
&nbsp; * @param con连接对象<a>""""r</a><br />
&nbsp; */<br />
&nbsp;public void freeConnection(String name, Connection con) {<br />
&nbsp;&nbsp;DBConnectionPool pool = (DBConnectionPool) pools.get(name);<br />
&nbsp;&nbsp;if (pool != null) {<br />
&nbsp;&nbsp;&nbsp;pool.freeConnection(con);<br />
&nbsp;&nbsp;}<br />
&nbsp;}</p>
<p>&nbsp;/**<br />
&nbsp; * 获得一个可用的(空闲的)连接.如果没有可用连接,且已有连接数小于最大连接数 053 * 限制,则创建并返回新连<br />
&nbsp; * @param name在属性文件中定义的连接池名字 056 *<br />
&nbsp; * @return Connection 可用连接或null 057<br />
&nbsp; */<br />
&nbsp;public Connection getConnection(String name) {<br />
&nbsp;&nbsp;DBConnectionPool pool = (DBConnectionPool) pools.get(name);<br />
&nbsp;&nbsp;if (pool != null) {<br />
&nbsp;&nbsp;&nbsp;return pool.getConnection();<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;return null;<br />
&nbsp;}</p>
<p>&nbsp;/**<br />
&nbsp; * 获得一个可用连接.若没有可用连接,且已有连接数小于最大连接数限制, <br />
&nbsp; * 则创建并返回新连接.否则,在指定的时间内等待其它线程释放连接.<br />
&nbsp; * @param name 连接池名字 071 *<br />
&nbsp; * @param time以毫秒计的等待时间<a>""""r</a><br />
&nbsp; * @return Connection 可用连接或null<br />
&nbsp; */<br />
&nbsp;public Connection getConnection(String name, long time) {<br />
&nbsp;&nbsp;DBConnectionPool pool = (DBConnectionPool) pools.get(name);<br />
&nbsp;&nbsp;if (pool != null) {<br />
&nbsp;&nbsp;&nbsp;return pool.getConnection(time);<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;return null;<br />
&nbsp;}</p>
<p>&nbsp;/**<br />
&nbsp; * 关闭所有连接,撤销驱动程序的注册<a>""""r</a><br />
&nbsp; */<br />
&nbsp;public synchronized void release() {<br />
&nbsp;&nbsp;// 等待直到最后一个客户程序调用<br />
&nbsp;&nbsp;if (--clients != 0) {<br />
&nbsp;&nbsp;&nbsp;return;<br />
&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;Enumeration allPools = pools.elements();<br />
&nbsp;&nbsp;while (allPools.hasMoreElements()) {<br />
&nbsp;&nbsp;&nbsp;DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();<br />
&nbsp;&nbsp;&nbsp;pool.release();<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;Enumeration allDrivers = drivers.elements();<br />
&nbsp;&nbsp;while (allDrivers.hasMoreElements()) {<br />
&nbsp;&nbsp;&nbsp;Driver driver = (Driver) allDrivers.nextElement();<br />
&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;DriverManager.deregisterDriver(driver);<br />
&nbsp;&nbsp;&nbsp;&nbsp;log("撤销JDBC驱动程序 " + driver.getClass().getName() + "的注册");<br />
&nbsp;&nbsp;&nbsp;} catch (SQLException e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;log(e, "无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName());<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;}<br />
&nbsp;}</p>
<p>&nbsp;/**<br />
&nbsp; * 根据指定属性创建连接池实例.<br />
&nbsp; * @param props 连接池属性 113<br />
&nbsp; */<br />
&nbsp;private void createPools(Properties props) {<br />
&nbsp;&nbsp;Enumeration propNames = props.propertyNames();<br />
&nbsp;&nbsp;while (propNames.hasMoreElements()) {<br />
&nbsp;&nbsp;&nbsp;String name = (String) propNames.nextElement();<br />
&nbsp;&nbsp;&nbsp;if (name.endsWith(".url")) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;String poolName = name.substring(0, name.lastIndexOf("."));<br />
&nbsp;&nbsp;&nbsp;&nbsp;String url = props.getProperty(poolName + ".url");<br />
&nbsp;&nbsp;&nbsp;&nbsp;if (url == null) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;log("没有为连接池" + poolName + "指定URL");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;continue;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;String user = props.getProperty(poolName + ".user");<br />
&nbsp;&nbsp;&nbsp;&nbsp;String password = props.getProperty(poolName + ".password");<br />
&nbsp;&nbsp;&nbsp;&nbsp;String maxconn = props.getProperty(poolName + ".maxconn", "0");<br />
&nbsp;&nbsp;&nbsp;&nbsp;int max;<br />
&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;max = Integer.valueOf(maxconn).intValue();<br />
&nbsp;&nbsp;&nbsp;&nbsp;} catch (NumberFormatException e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;log("错误的最大连接数限制: " + maxconn + " .连接池: " + poolName);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;max = 0;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;DBConnectionPool pool = new DBConnectionPool(poolName, url,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user, password, max);<br />
&nbsp;&nbsp;&nbsp;&nbsp;pools.put(poolName, pool);<br />
&nbsp;&nbsp;&nbsp;&nbsp;log("成功创建连接池" + poolName);<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;}<br />
&nbsp;}</p>
<p>&nbsp;/**<br />
&nbsp; * 读取属性完成初始化<br />
&nbsp; */<br />
&nbsp;private void init() {<br />
&nbsp;&nbsp;InputStream is = getClass().getResourceAsStream("/db.properties");<br />
&nbsp;&nbsp;Properties dbProps = new Properties();<br />
&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;dbProps.load(is);<br />
&nbsp;&nbsp;} catch (Exception e) {<br />
&nbsp;&nbsp;&nbsp;System.err.println("不能读取属性文件. "+"请确保db.properties在CLASSPATH指定的路径中");<br />
&nbsp;&nbsp;&nbsp;return;<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;String logFile = dbProps.getProperty("logfile","DBConnectionManager.log");<br />
&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;log = new PrintWriter(new FileWriter(logFile, true), true);<br />
&nbsp;&nbsp;} catch (IOException e) {<br />
&nbsp;&nbsp;&nbsp;System.err.println("无法打开日志文件: " + logFile);<br />
&nbsp;&nbsp;&nbsp;log = new PrintWriter(System.err);<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;loadDrivers(dbProps);<br />
&nbsp;&nbsp;createPools(dbProps);<br />
&nbsp;}</p>
<p>&nbsp;/**<br />
&nbsp; * 装载和注册所有JDBC驱动程序<br />
&nbsp; * @param props属性<br />
&nbsp; */<br />
&nbsp;private void loadDrivers(Properties props) {<br />
&nbsp;&nbsp;String driverClasses = props.getProperty("drivers"); <br />
&nbsp;&nbsp;StringTokenizer st = new StringTokenizer(driverClasses);<br />
&nbsp;&nbsp;while (st.hasMoreElements()) {<br />
&nbsp;&nbsp;&nbsp;String driverClassName = st.nextToken().trim(); <br />
&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;Driver driver = (Driver) Class.forName(driverClassName).newInstance();<br />
&nbsp;&nbsp;&nbsp;&nbsp;DriverManager.registerDriver(driver);<br />
&nbsp;&nbsp;&nbsp;&nbsp;drivers.addElement(driver);<br />
&nbsp;&nbsp;&nbsp;&nbsp;log("成功注册JDBC驱动程序" + driverClassName);<br />
&nbsp;&nbsp;&nbsp;} catch (Exception e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();<br />
&nbsp;&nbsp;&nbsp;&nbsp;log("无法注册JDBC驱动程序: " + driverClassName + ", 错误: " + e);<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;}<br />
&nbsp;}</p>
<p>&nbsp;/**<br />
&nbsp; * 将文本信息写入日志文件<br />
&nbsp; */<br />
&nbsp;private void log(String msg) {<br />
&nbsp;&nbsp;log.println(new Date() + ": " + msg);<br />
&nbsp;}</p>
<p>&nbsp;/**<br />
&nbsp; * 将文本信息与异常写入日志文件<br />
&nbsp; */<br />
&nbsp;private void log(Throwable e, String msg) {<br />
&nbsp;&nbsp;log.println(new Date() + ": " + msg);<br />
&nbsp;&nbsp;e.printStackTrace(log);<br />
&nbsp;}</p>
<p>&nbsp;// ///////////////////////////////////////////////////////////////////////////////////////////////////////<br />
&nbsp;// ///////////////////////////////////////////////////////////////////////////////////////////////////////<br />
&nbsp;/*<br />
&nbsp; * DBConnectionPool实现，它表示指向某个数据库的连接池。数据库由JDBC URL标识。一个JDBCURL由三部分组成：协议标识（总是jdbc），<br />
&nbsp; * 驱动程序标识（如odbc、idb、oracle等），数据库标识（其格式依赖于驱动程序）。例如，jdbc:odbc:demo，即是一个指向demo数据 <br />
&nbsp; * 库的JDBCURL，而且访问该数据库要使用JDBC-ODBC驱动程序。每个连接池都有一个供客户程序使用的名字以及可选的用户帐号、密码、最<br />
&nbsp; * 大连接数限制。如果Web应用程序所支持的某些数据库操作可以被所有用户执行，而其它一些操作应由特别许可的用户执行，则可以为两类操作<br />
&nbsp; * 分别定义连接池，两个连接池使用相同的JDBC URL，但使用不同的帐号和密码。类DBConnectionPool的建构函数需要上述所有数据作为其<br />
&nbsp; * 参数。客户程序可以使用DBConnectionPool<br />
&nbsp; * 类提供的两个方法获取可用连接。两者的共同之处在于：如连接池中存在可用连接，则直接返回，否则创建新的连接并返回。如果没有可用连接<br />
&nbsp; * 且已有连接总数等于最大限制数，第一个方法将直接返回null，而第二个方法将等待直到有可用连接为止。所有的可用连接对象均登记在名为<br />
&nbsp; * freeConnections的向量（Vector）中。如果向量中有多于一个的连接，getConnection()总是选取第一个。同时，由于新的可用连接总<br />
&nbsp; * 是从尾部加入向量，从而使得数据库连接由于长时间闲置而被关闭的风险减低到最小程度。 第一个getConnection()在返回可用连接给客户<br />
&nbsp; * 程序之前，调用了isClosed()方法验证连接仍旧有效。如果该连接被关闭或触发异常，getConnection()递归地调用自己以尝试获取另外的<br />
&nbsp; * 可用连接。如果在向量freeConnections中不存在任何可用连接，getConnection()方法检查是否已经指定最大连接数限制。如已经指定，<br />
&nbsp; * 则检查当前连接数是否已经到达极限。此处maxConn为0表示没有限制。如果没有指定最大连接数限制或当前连接数小于该值，该方法尝试创建<br />
&nbsp; * 新的连接。如创建成功，则增加已使用连接的计数并返回，否则返回空值。创建新连接由newConnection()方法实现。<br />
&nbsp; * 创建过程与是否已经指定数据库帐号、密码有关。JDBC的DriverManager类提供多个getConnection()方法，这些方法要用到JDBC URL<br />
&nbsp; * 与其它一些参数，如用户帐号和密码等。DriverManager将使用指定的JDBC URL确定适合于目标数据库的驱动程序及建立连接。<br />
&nbsp; * 第二个getConnection()方法需要一个以毫秒为单位的时间参数，该参数表示客户程序能够等待的最长时间。建立连接的具体操<br />
&nbsp; * 作仍旧由第一个getConnection()方法实现。该方法执行时先将startTime初始化为当前时间。在while循环中尝试获得一个连接。如果失<br />
&nbsp; * 败，则以给定的时间值为参数调用wait()。wait()的返回可能是由于其它线程调用notify()或notifyAll()，也可能是由于预定时间已到。<br />
&nbsp; * 为找出wait()返回的真正原因，程序用当前时间减开始时间（startTime），如差值大于预定时间则返回空值，否则再次调用getConnection()。<br />
&nbsp; * 把空闲的连接登记到连接池由freeConnection()方法实现，它的参数为返回给连接池的连接对象。该对象被加入到freeConnections<br />
&nbsp; * 向量的末尾，然后减少已使用连接计数。调用notifyAll()是为了通知其它正在等待可用连接的线程。 许多Servlet引擎为实现安全关闭提供<br />
&nbsp; * 多种方法。数据库连接池需要知道该事件以保证所有连接能够正常关闭。DBConnectionManager类负协调整个关闭过程，但关闭连接池中所有连<br />
&nbsp; * 接的任务则由DBConnectionPool类负责。release()方法供DBConnectionManager调用。该方法遍历freeConnections向量并关闭所有连接，<br />
&nbsp; * 然后从向量中删除这些连接。<br />
&nbsp; */</p>
<p>&nbsp;/**<br />
&nbsp; * 此内部类定义了一个连接池.它能够根据要求创建新连接,直到预定的最<a>""""r</a><br />
&nbsp; */<br />
&nbsp;class DBConnectionPool {<br />
&nbsp;&nbsp;private int checkedOut;</p>
<p>&nbsp;&nbsp;private Vector freeConnections = new Vector();</p>
<p>&nbsp;&nbsp;private int maxConn;</p>
<p>&nbsp;&nbsp;private String name;</p>
<p>&nbsp;&nbsp;private String password;</p>
<p>&nbsp;&nbsp;private String URL;</p>
<p>&nbsp;&nbsp;private String user;</p>
<p>&nbsp;&nbsp;/**<br />
&nbsp;&nbsp; * 创建新的连接池<br />
&nbsp;&nbsp; * @param name连接池名字<br />
&nbsp;&nbsp; * @param URL数据库的JDBC URL<br />
&nbsp;&nbsp; * @param user数据库帐号,或 null<br />
&nbsp;&nbsp; * @param password密码,或 null<br />
&nbsp;&nbsp; * @param maxConn此连接池允许建立的最大连接数<br />
&nbsp;&nbsp; */<br />
&nbsp;&nbsp;public DBConnectionPool(String name, String URL, String user,<br />
&nbsp;&nbsp;&nbsp;&nbsp;String password, int maxConn) {<br />
&nbsp;&nbsp;&nbsp;this.name = name;<br />
&nbsp;&nbsp;&nbsp;this.URL = URL;<br />
&nbsp;&nbsp;&nbsp;this.user = user;<br />
&nbsp;&nbsp;&nbsp;this.password = password;<br />
&nbsp;&nbsp;&nbsp;this.maxConn = maxConn;<br />
&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;/**<br />
&nbsp;&nbsp; * 将不再使用的连接返回给连接池<br />
&nbsp;&nbsp; * @param con客户程序释放的连接<br />
&nbsp;&nbsp; */<br />
&nbsp;&nbsp;public synchronized void freeConnection(Connection con) {<br />
&nbsp;&nbsp;&nbsp;// 将指定连接加入到向量末尾<br />
&nbsp;&nbsp;&nbsp;freeConnections.addElement(con);<br />
&nbsp;&nbsp;&nbsp;checkedOut--;<br />
&nbsp;&nbsp;&nbsp;notifyAll();<br />
&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;/**<br />
&nbsp;&nbsp; * 从连接池获得一个可用连接.如没有空闲的连接且当前连接数小于最大连接 数限制,则创建新连接.<br />
&nbsp;&nbsp; * 如原来登记为可用的连接不再有效,则从向量删除之,<br />
&nbsp;&nbsp; * 然后递归调用自己以尝试新的可用连接.<br />
&nbsp;&nbsp; */<br />
&nbsp;&nbsp;public synchronized Connection getConnection() {<br />
&nbsp;&nbsp;&nbsp;Connection con = null;<br />
&nbsp;&nbsp;&nbsp;if (freeConnections.size() &gt; 0) {// 获取向量中第一个可用连接<br />
&nbsp;&nbsp;&nbsp;&nbsp;con = (Connection) freeConnections.firstElement();<br />
&nbsp;&nbsp;&nbsp;&nbsp;freeConnections.removeElementAt(0);<br />
&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (con.isClosed()) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;log("从连接池" + name + "删除一个无效连接");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// 递归调用自己,尝试再次获取可用连接<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;con = getConnection();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;} catch (SQLException e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;log("从连接池" + name + "删除一个无效连接");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// 递归调用自己,尝试再次获取可用连接<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;con = getConnection();<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;} else if (maxConn == 0 || checkedOut &lt; maxConn) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;con = newConnection();<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;if (con != null) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;checkedOut++;<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;return con;<br />
&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;/**<br />
&nbsp;&nbsp; * 从连接池获取可用连接.可以指定客户程序能够等待的最长时间 参见前一个getConnection()方法.<br />
&nbsp;&nbsp; * @param timeout以毫秒计的等待时间限制<br />
&nbsp;&nbsp; */<br />
&nbsp;&nbsp;public synchronized Connection getConnection(long timeout) {<br />
&nbsp;&nbsp;&nbsp;long startTime = new Date().getTime();<br />
&nbsp;&nbsp;&nbsp;Connection con;<br />
&nbsp;&nbsp;&nbsp;while ((con = getConnection()) == null) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;wait(timeout);<br />
&nbsp;&nbsp;&nbsp;&nbsp;} catch (InterruptedException e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;if ((new Date().getTime() - startTime) &gt;= timeout) {// wait()返回的原因是超时<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return null;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;return con;<br />
&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;/**<br />
&nbsp;&nbsp; * 关闭所有连接<br />
&nbsp;&nbsp; */<br />
&nbsp;&nbsp;public synchronized void release() {<br />
&nbsp;&nbsp;&nbsp;Enumeration allConnections = freeConnections.elements();<br />
&nbsp;&nbsp;&nbsp;while (allConnections.hasMoreElements()) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;Connection con = (Connection) allConnections.nextElement();<br />
&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;con.close();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;log("关闭连接池" + name + "中的一个连接");<br />
&nbsp;&nbsp;&nbsp;&nbsp;} catch (SQLException e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;log(e, "无法关闭连接池" + name + "中的连接");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;freeConnections.removeAllElements();<br />
&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;/**<br />
&nbsp;&nbsp; * 创建新的连接<br />
&nbsp;&nbsp; */<br />
&nbsp;&nbsp;private Connection newConnection() {<br />
&nbsp;&nbsp;&nbsp;Connection con = null;<br />
&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;if (user==null||"".equals(user)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;con = DriverManager.getConnection(URL);<br />
&nbsp;&nbsp;&nbsp;&nbsp;} else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;con = DriverManager.getConnection(URL, user, password);<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;log("连接池" + name + "创建一个新的连接");<br />
&nbsp;&nbsp;&nbsp;} catch (SQLException e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;log(e, "无法创建下列URL的连接: " + URL);<br />
&nbsp;&nbsp;&nbsp;&nbsp;return null;<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;return con;<br />
&nbsp;&nbsp;}<br />
&nbsp;}</p>
<p>&nbsp;/////////////////////////////////////////////////////////////////////////////////////////////<br />
&nbsp;/////////////////////////////////////////////////////////////////////////////////////////////<br />
}<br />
<br />
在sqlserver2000，tomcat5.5验证通过</p>
<p>方法调用！</p>
<p>package com.xinnuo.jdbc;</p>
<p>import java.sql.Connection;<br />
import java.sql.ResultSet;<br />
import java.sql.SQLException;<br />
import java.sql.Statement;</p>
public class DBConn {<br />
&nbsp;private DBConnectionManager connMgr = null;<br />
&nbsp;private Connection conn = null;<br />
&nbsp;private Statement stat = null;<br />
&nbsp;private ResultSet rs = null;<br />
&nbsp;public DBConn() {<br />
&nbsp;&nbsp;connMgr = DBConnectionManager.getInstance();<br />
&nbsp;}<br />
&nbsp;public ResultSet executeQuery(String strSQL) throws SQLException {<br />
&nbsp;&nbsp;this.conn = connMgr.getConnection("access");<br />
&nbsp;&nbsp;this.stat = this.conn.createStatement();<br />
&nbsp;&nbsp;this.rs = this.stat.executeQuery(strSQL);<br />
&nbsp;&nbsp;return this.rs;<br />
&nbsp;}<br />
&nbsp;public void execute(String strSQL) throws SQLException {<br />
&nbsp;&nbsp;this.conn = connMgr.getConnection("access");<br />
&nbsp;&nbsp;this.stat = this.conn.createStatement();<br />
&nbsp;&nbsp;this.stat.execute(strSQL);<br />
&nbsp;}<br />
&nbsp;public void executeUpdate(String strSQL) throws SQLException {<br />
&nbsp;&nbsp;this.conn = connMgr.getConnection("access");<br />
&nbsp;&nbsp;this.stat = this.conn.createStatement();<br />
&nbsp;&nbsp;this.stat.executeUpdate(strSQL);<br />
&nbsp;}<br />
&nbsp;public Connection getConnection(){<br />
&nbsp;&nbsp;this.conn = connMgr.getConnection("access");<br />
&nbsp;&nbsp;return this.conn;<br />
&nbsp;}<br />
&nbsp;public void free(){<br />
&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;if (this.rs != null) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;this.rs.close();<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;if (this.stat != null) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;this.stat.close();<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;} catch (SQLException e) {<br />
&nbsp;&nbsp;&nbsp;e.printStackTrace();<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;connMgr.freeConnection("access", this.conn);<br />
&nbsp;}<br />
}
<img src ="http://www.blogjava.net/sealyu/aggbug/259574.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2009-03-13 16:58 <a href="http://www.blogjava.net/sealyu/archive/2009/03/13/259574.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>SQL Server / MySQL 表名长度限制</title><link>http://www.blogjava.net/sealyu/archive/2009/03/04/257793.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Wed, 04 Mar 2009 07:12:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2009/03/04/257793.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/257793.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2009/03/04/257793.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/257793.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/257793.html</trackback:ping><description><![CDATA[SQL Server表名长度限制为：128字符<br />
MySQL数据库名和表名长度限制为：64字符。<br />
<br />
<img src ="http://www.blogjava.net/sealyu/aggbug/257793.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2009-03-04 15:12 <a href="http://www.blogjava.net/sealyu/archive/2009/03/04/257793.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Ubuntu下SQuirrel连接Microsoft SQL Server（很好的客户端）</title><link>http://www.blogjava.net/sealyu/archive/2009/01/14/251217.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Wed, 14 Jan 2009 02:02:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2009/01/14/251217.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/251217.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2009/01/14/251217.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/251217.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/251217.html</trackback:ping><description><![CDATA[今天终于搞定SQuirrel了，这样就可以把项目的开发平台全部迁移到ubuntu下面了，经过测试，项目编译的时间整整节省了一半，jboss的启动时间也省了很多，现在完整编译由以前的十多分钟变为3分钟多点，看来ext3的文件系统比NTFS还是效率高很多啊。<br />
顺便把安装配置SQuirrel的过程中遇到到的问题记录一下，以免忘记：<br />
1。我安装的版本是SQuirrel2.6.8， 在安装完成后启动，显示出来的只有一个空窗口，除了标题栏没任何东西，Google了一下，有人说是jdk版本的问题，由于项目需要，必须使用jdk5，看来只有安装两个jdk了。 可以这么作，原有jdk及环境变量保持不变，再安装一个jdk6，然后手动创建一个launcher，启动参数设置为：/usr/lib/jvm/java-6-sun/bin/java -jar /home/sealyu/tools/SQuirreL/squirrel-sql.jar 。<br />
2。不知道是否由于版本的原因，没找到使用文档，SQuirrel官方网站也没找到。后来自己摸索了一下，想要连接到Microsoft SQL Server（这里我用的版本是2005），下载了最新的jtds驱动，我的是jtds1.2.2.jar。将之放到SQuirrel_home/lib下面，这样就能自动检测到驱动，打开SQuirrel后，在jTDS Microsoft SQL 右键，选择Modify Driver, 在 Extra Class Path 中选出你的jtds架包，List Drivers，这样你就能在下面的下拉框中看到驱动的主类。点击确定按钮，这时候左边树形菜单里面对应的条目前方就由红色的小叉变为绿色的对号了。<br />
3。新建一个Alias，输入你要连接数据库的信息，connect即可使用。<br />
<br />
<br />
<img src ="http://www.blogjava.net/sealyu/aggbug/251217.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2009-01-14 10:02 <a href="http://www.blogjava.net/sealyu/archive/2009/01/14/251217.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>SQL2005开发版安装中“性能监视器计数器要求（错误）”和“com+目录问题警告处理”问题的解决(转)</title><link>http://www.blogjava.net/sealyu/archive/2008/12/12/245888.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Fri, 12 Dec 2008 03:29:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2008/12/12/245888.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/245888.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2008/12/12/245888.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/245888.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/245888.html</trackback:ping><description><![CDATA[出现此类问题一般都是在非法卸载sql2005出现的<br />
<br />
<img src="http://images.cnblogs.com/cnblogs_com/submaie/snap016.gif" alt="" border="0" /><br />
<br />
在 &#8220;开始&#8221; --&gt;&nbsp; &#8220;运行&#8221;中输入 regedit，开启注册表编辑器。<br />
<br />
定位到<br />
[HKEY_LOCAL_MACHINE"SOFTWARE"Microsoft"Windows NT"CurrentVersion"Perflib<br />
处，在右边的树形目录下可以看到Perflib目录下有004和009两个子目录。<br />
<br />
在Sql Server 2005 的安装帮助文件中说的是需要查看009目录的注册表项，而我们大部分人使用的是简体中文的操作系统，所以不能按帮助中说的，而是需要注意004目录中的内容。<br />
<br />
打开004 目录中的内容，可以看到如下图：<br />
<br />
<img src="http://images.cnblogs.com/cnblogs_com/submaie/snap018.gif" alt="" border="0" /><br />
<br />
我们分别双击 &#8220;Counter&#8221; 项 和 &#8220;Help&#8221; 项，察看其中的最后的数字，如下图：<br />
<br />
Counter 项的内容：<br />
<br />
<img src="http://images.cnblogs.com/cnblogs_com/submaie/snap019.gif" alt="" border="0" /><br />
<br />
<br />
Helper 项内容<br />
<br />
<img src="http://images.cnblogs.com/cnblogs_com/submaie/snap020.gif" alt="" border="0" /><br />
<br />
这时候，我们知道，Counter 项的数字是5556，Helper项的内容是5557。<br />
<br />
然后，操作注册表编辑器的左边的目录树，定位到Perflib目录下，并注意检查右边窗口的 &#8220;Laster Counter&#8221;项和&#8220;Laster
Help&#8221;项的值，并把Laster Counter的值改成刚才记录下的Counter值5556，把Laster Help 的值改成刚才记下的
Help的值5557。<br />
<br />
要注意的是，修改数字的时候，输入的时候必须选则基数是 &#8220;十进制&#8221;，否则数字将不匹配，Sql Server 2005 检查将再次失败。<br />
<br />
然后关闭注册表编辑器，开始安装 Sql Server 2005 ，绝对可以安装成功。
<img src ="http://www.blogjava.net/sealyu/aggbug/245888.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2008-12-12 11:29 <a href="http://www.blogjava.net/sealyu/archive/2008/12/12/245888.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>RedHat AS4 下安装Bugzilla后不能连接MySQL问题的解决方法</title><link>http://www.blogjava.net/sealyu/archive/2008/07/20/216263.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Sun, 20 Jul 2008 15:44:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2008/07/20/216263.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/216263.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2008/07/20/216263.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/216263.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/216263.html</trackback:ping><description><![CDATA[在RedHat AS4上安装Bugzilla时，<br />
在安装完对应的perl模块后，在localconfig文件中配置mysql的对应信息，<br />
继续运行checksetup.pl,出现如下错误：<br />
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)<br />
<br />
但是Mysql已经安装并且能正常运行，后来发现Bugzilla 默认检查Mysql时是使用/var/lib/mysql/mysql.sock进行连接，<br />
而我使用源码编译安装的Mysql是使用/tmp/mysql.sock 进行连接，所以Bugzilla检查Mysql设置时会出现连接错误。<br />
解决方法很简单：<br />
ln -s /tmp/mysql.sock /var/lib/mysql/mysql.sock<br />
这样每次Bugzilla连接时就会使用/tmp/mysql.sock进行连接，安装成功。<br />
<br />
<img src ="http://www.blogjava.net/sealyu/aggbug/216263.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2008-07-20 23:44 <a href="http://www.blogjava.net/sealyu/archive/2008/07/20/216263.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>在Redhat AS4上源码编译安装MySQL</title><link>http://www.blogjava.net/sealyu/archive/2008/07/20/216256.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Sun, 20 Jul 2008 14:32:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2008/07/20/216256.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/216256.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2008/07/20/216256.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/216256.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/216256.html</trackback:ping><description><![CDATA[<p>by Seal （Haibo Yu）2008-7-20<br />
</p>
<p><br />
1&gt;将mysql安装文件(本人使用mysql5.0.51a-linux-i686-glibc23.tar.gz)解压到对应目录，在此为 /home/seal/mysql<br />
</p>
<p>2&gt;进入源码目录编译安装</p>
<p>CODE:</p>
<p>#cd /home/seal/mysql <br />
#./configure --prefix=/usr/local/mysql --with-charset=gbk&nbsp; |注:配置Mysql安装路径并且支持中文<br />
#make&nbsp; |注:编译<br />
#make install&nbsp; |注:编译安装</p>
<p>3&gt;替换/etc/my.cnf文件,进入源码包,执行命令</p>
<p>CODE:</p>
<p>#cd /home/seal/mysql<br />
#cp support-files/my-medium.cnf /etc/my.cnf</p>
<p>4&gt;建立MySQL使用者和群组:
</p>
<p>CODE:</p>
#groupadd mysql<br />
#useradd -g mysql mysql <br />
<p>5&gt;完成以上操作以后进行初始化数据库,进入已经安装好的mysql目录</p>
<p>CODE:</p>
<p>#cd /usr/local/mysql<br />
#bin/mysql_install_db --user=mysql&nbsp; |注:--user=mysql 初始化表并且规定用mysql用户<br />
6&gt;设置给mysql和root用户设定访问权限 我们先进入mysql目录</p>
<p>CODE:</p>
<p>#cd /usr/local/mysql<br />
#chown -R root /usr/local/mysql&nbsp;&nbsp; |注:设定root能访问/usr/local/mysq<br />
#chown -R mysql /usr/local/mysql/var&nbsp;&nbsp; |注:设定mysql用户能访问/usr/local/mysql/var<br />
#chgrp -R mysql /usr/local/mysql&nbsp;&nbsp;&nbsp; |注:设定mysql组能够访问/usr/local/mysq<br />
7&gt;启动mysql,进入已经安装好的目录</p>
<p>CODE:</p>
<p>#cd /usr/local/mysql<br />
#bin/mysqld_safe --user=mysql &amp;</p>
<p>8&gt;<br />
修改mysql数据库超级用户root的缺省密码: <br />
/usr/local/mysql/bin/mysqladmin -u root password 'mysql'</p>
<p>关闭mysql服务器 <br />
cd /usr/local/mysql/bin <br />
./mysqladmin -u root -p&nbsp;&nbsp;&nbsp; shutdown&nbsp; </p>
<p>9&gt;设定开机就启动mysql,进入源码目录下</p>
<p># cd /home/seal/mysql<br />
# cp support-files/mysql.server /etc/init.d/mysql</p>
# chmod +x /etc/init.d/mysql<br />
# chkconfig --level 345 mysql on<br />
# service mysql restart<br />
Shutting down MySQL.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [&nbsp; 确定&nbsp; ]<br />
Starting MySQL&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [&nbsp; 确定&nbsp; ]<br />
[root@localhost mysql]#<br />
10&gt;设置Mysql远程访问：<br />
在启动mysql后：<br />
mysql&gt;<span style="font-size: 9.5pt; color: #333333;">GRANT ALL PRIVILEGES ON *.* TO &#8216;myuser&#8217;@'%&#8217; IDENTIFIED BY &#8216;mypassword&#8217; WI<br />
TH GRANT OPTION;<br />
mysql&gt;Flush Privileges;<br />
<br />
安装完毕。<br />
<br />
</span>
<img src ="http://www.blogjava.net/sealyu/aggbug/216256.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2008-07-20 22:32 <a href="http://www.blogjava.net/sealyu/archive/2008/07/20/216256.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>mysql开启远程连接的方法</title><link>http://www.blogjava.net/sealyu/archive/2008/07/15/215088.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Tue, 15 Jul 2008 14:36:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2008/07/15/215088.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/215088.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2008/07/15/215088.html#Feedback</comments><slash:comments>3</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/215088.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/215088.html</trackback:ping><description><![CDATA[<p style="margin: 3pt 0cm 0pt; line-height: 185%; text-align: left;" align="left"><strong><span style="color: #333333; line-height: 185%;">解决</span></strong><strong><span style="color: #333333; line-height: 185%;">MySQL</span></strong><strong><span style="color: #333333; line-height: 185%;">不允许从远程访问的方法</span></strong></p>
<p style="margin: 0cm 0cm 12pt; text-align: left;" align="left"><span style="font-size: 9.5pt; color: #333333;">解决方法：</span><span style="font-size: 9.5pt; color: #333333;"><br />
1</span><span style="font-size: 9.5pt; color: #333333;">。</span><span style="font-size: 9.5pt; color: #333333;">改表法。可能是你的帐号不允许从远程登陆，只能在</span><span style="font-size: 9.5pt; color: #333333;">localhost</span><span style="font-size: 9.5pt; color: #333333;">。这个时候只要在</span><span style="font-size: 9.5pt; color: #333333;">localhost</span><span style="font-size: 9.5pt; color: #333333;">的那台电脑，登入</span><span style="font-size: 9.5pt; color: #333333;">mysql</span><span style="font-size: 9.5pt; color: #333333;">后，更改</span><span style="font-size: 9.5pt; color: #333333;"> &#8220;mysql&#8221; </span><span style="font-size: 9.5pt; color: #333333;">数据库里的</span><span style="font-size: 9.5pt; color: #333333;"> &#8220;user&#8221; </span><span style="font-size: 9.5pt; color: #333333;">表里的</span><span style="font-size: 9.5pt; color: #333333;"> &#8220;host&#8221; </span><span style="font-size: 9.5pt; color: #333333;">项，从</span><span style="font-size: 9.5pt; color: #333333;">&#8220;localhost&#8221;</span><span style="font-size: 9.5pt; color: #333333;">改称</span><span style="font-size: 9.5pt; color: #333333;">&#8220;%&#8221;</span></p>
<div>
<table style="background: black none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; width: 95%;" border="0" cellpadding="0" cellspacing="1" width="95%">
    <tbody>
        <tr>
            <td style="padding: 0cm; background: #e6e6e6 none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; width: 100%;" width="100%">
            <p style="margin: 0cm 0cm 0pt; text-align: left;" align="left"><span style="font-size: 9.5pt; color: #333333;">mysql -u root -pvmwaremysql&gt;use mysql;<br />
            mysql&gt;update user set host = &#8216;%&#8217; where user = &#8216;root&#8217;;<br />
            mysql&gt;select host, user from user;</span></p>
            </td>
        </tr>
    </tbody>
</table>
</div>
<p>2. <span style="font-size: 9.5pt; color: #333333;">授权法。例如，你想</span><span style="font-size: 9.5pt; color: #333333;">myuser</span><span style="font-size: 9.5pt; color: #333333;">使用</span><span style="font-size: 9.5pt; color: #333333;">mypassword</span><span style="font-size: 9.5pt; color: #333333;">从任何主机连接到</span><span style="font-size: 9.5pt; color: #333333;">mysql</span><span style="font-size: 9.5pt; color: #333333;">服务器的话。</span></p>
<div>
<table style="background: black none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; width: 95%;" border="0" cellpadding="0" cellspacing="1" width="95%">
    <tbody>
        <tr>
            <td style="padding: 0cm; background: #e6e6e6 none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; width: 100%;" width="100%">
            <p style="margin: 0cm 0cm 0pt; text-align: left;" align="left"><span style="font-size: 9.5pt; color: #333333;">GRANT ALL PRIVILEGES ON *.* TO &#8216;myuser&#8217;@'%&#8217; IDENTIFIED BY &#8216;mypassword&#8217; WI<br />
            TH GRANT OPTION;</span></p>
            </td>
        </tr>
    </tbody>
</table>
</div>
<p><span style="font-size: 9.5pt; color: #333333;">如果你想允许用户</span><span style="font-size: 9.5pt; color: #333333;">myuser</span><span style="font-size: 9.5pt; color: #333333;">从</span><span style="font-size: 9.5pt; color: #333333;">ip</span><span style="font-size: 9.5pt; color: #333333;">为</span><span style="font-size: 9.5pt; color: #333333;">192.168.1.6</span><span style="font-size: 9.5pt; color: #333333;">的主机连接到</span><span style="font-size: 9.5pt; color: #333333;">mysql</span><span style="font-size: 9.5pt; color: #333333;">服务器，并使用</span><span style="font-size: 9.5pt; color: #333333;">mypassword</span><span style="font-size: 9.5pt; color: #333333;">作为密码</span></p>
<div>
<table style="background: black none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; width: 95%;" border="0" cellpadding="0" cellspacing="1" width="95%">
    <tbody>
        <tr>
            <td style="padding: 0cm; background: #e6e6e6 none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; width: 100%;" width="100%">
            <p style="margin: 0cm 0cm 0pt; text-align: left;" align="left"><span style="font-size: 9.5pt; color: #333333;">GRANT ALL PRIVILEGES ON *.* TO &#8216;myuser&#8217;@'192.168.1.3&#8242; IDENTIFIED BY<br />
            &#8216;mypassword&#8217; WITH GRANT OPTION; </span></p>
            </td>
        </tr>
    </tbody>
</table>
</div>
<span style="font-size: 9.5pt; color: #333333;">我用的第一个方法</span><span style="font-size: 9.5pt; color: #333333;">,</span><span style="font-size: 9.5pt; color: #333333;">刚开始发现不行</span><span style="font-size: 9.5pt; color: #333333;">,</span><span style="font-size: 9.5pt; color: #333333;">在网上查了一下</span><span style="font-size: 9.5pt; color: #333333;">,</span><span style="font-size: 9.5pt; color: #333333;">少执行一个语句</span><span style="font-size: 9.5pt; color: #333333;"> mysql&gt;FLUSH&nbsp;&nbsp; PRIVILEGES<br />
</span><span style="font-size: 9.5pt; color: #333333;">使修改生效</span><span style="font-size: 9.5pt; color: #333333;">.</span><span style="font-size: 9.5pt; color: #333333;">就可以了</span>
<img src ="http://www.blogjava.net/sealyu/aggbug/215088.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2008-07-15 22:36 <a href="http://www.blogjava.net/sealyu/archive/2008/07/15/215088.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>SQL Server日期处理datetime和date之间的相互转换</title><link>http://www.blogjava.net/sealyu/archive/2008/07/03/212308.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Thu, 03 Jul 2008 05:38:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2008/07/03/212308.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/212308.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2008/07/03/212308.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/212308.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/212308.html</trackback:ping><description><![CDATA[<p><font size="1"><span>日期是数据处理中经常使用到的信息之一。生日、数据处理时间、计划的预计完成时间，按年、季、月的统
计，这些都属于日期处理的范畴。由于日期中包含了年、季、月、日等众多信息，不同的国家对日期格式、日期文字描述及星期有不同的规定，因此产生了日期处理
的复杂性。本章主要讨论在</span>SQL Server数据库中对日期的各种处理方法。</font></p>
<h2 align="center"><font face="宋体, MS Song" size="1">日期类型概述</font></h2>
<p><font size="1">SQL Server中的日期类型包括datetime和smalldatetime，仅能处理可以识别为1753年～9999年间的日期的值，没有单独的日期型或时间型。</font></p>
<h4><font face="宋体, MS Song"><font size="1">1．datetime</font></font></h4>
<p><font size="1">datetime类型处理从1753年1月1日～9999年12月31日的日期和时间数据，精确度为百分之三秒。即：对于0.000～0.001、0.009的日期值，调整为0.000；对于0.002～0.004的日期值，调整为0.003；对于0.005～0.008的日期值，调整为0.007。</font></p>
<p><font size="1">例如，下面的代码在输入时，其时间精确度为百分之一秒，但经数据库保存后再显示出来，其结果就已经做了处理。</font></p>
<p><font face="Courier New" size="1">DECLARE @t TABLE(date char(21))</font></p>
<p><font face="Courier New" size="1">INSERT @t SELECT '1900-1-1 00:00:00.000'</font></p>
<p><font face="Courier New" size="1">...</font></p>
<p><font face="Courier New" size="1">INSERT @t SELECT '1900-1-1 00:00:00.009'</font></p>
<p><font size="1"><font face="Courier New">SELECT date,</font>转换后的日期<font face="Courier New">=CAST(date as datetime) FROM @t</font></font></p>
<p><font size="1"><font face="Courier New">/*--</font>结果</font></p>
<p><font size="1"><font face="Courier New">date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </font>转换后的日期</font></p>
<p><font face="Courier New" size="1">---------------------------------- ----------------------------</font></p>
<p><font face="Courier New" size="1">1900-1-1 00:00:00.000&nbsp;&nbsp;&nbsp; 1900-01-01 00:00:00.000<br />
...<br />
<font face="Courier New">1900-1-1 00:00:00.000&nbsp;&nbsp;&nbsp; 1900-01-01 00:00:00.010</font><br />
</font></p>
<font size="1"><font face="Courier New">--*/</font> </font>
<p><font size="1">datetime的存储长度为8字节，日期和时间各用4个字节存储，第一个4字节存储自1900年1月1日之前或之后的天数（以1900年1月1日为分界点，在1900年1月1日之前的日期的天数小于0，在1900年1月1日之后的日期的天数大于0）。另外一个4字节存储以午夜（00:00:00.000）后毫秒数所代表的每天的时间。</font></p>
<p><font size="1">例如，下面的代码演示了datetime变量中，仅包含单纯的日期和单纯的时间时，日期存储的十六进制存储表示结果。</font></p>
<p align="left"><font face="Courier New" size="1">DECLARE @dt datetime</font></p>
<p align="left"><font size="1"><font face="Courier New">--</font>单纯的日期</font></p>
<p align="left"><font face="Courier New" size="1">SET @dt='1900-1-2'</font></p>
<p align="left"><font face="Courier New" size="1">SELECT CAST(@dt as binary(8))</font></p>
<p align="left"><font size="1"><font face="Courier New">--</font>结果<font face="Courier New">: 0x0000000100000000</font></font></p>
<p align="left"><font size="1"><font face="Courier New">--</font>单纯的时间</font></p>
<p align="left"><font face="Courier New" size="1">SET @dt='00:00:01'</font></p>
<p align="left"><font face="Courier New" size="1">SELECT CAST(@dt as binary(8))</font></p>
<p align="left"><font size="1"><font face="Courier New">--</font>结果<font face="Courier New">: 0x000000000000012C</font></font></p>
<h4><font face="宋体, MS Song"><font size="1">2．smalldatetime</font></font></h4>
<p><font size="1">smalldatetime类型处理从1900年1月1日～2079年6月6 日的日期和时间数据，精确到分钟。29.998秒或更低的smalldatetime值向下舍入为最接近的分钟，29.999秒或更高的smalldatetime值向上舍入为最接近的分钟。</font></p>
<p><font size="1">smalldatetime的存储长度为4字节，第一个2字节存储自1900年1月1日之后的天数。另外一个2字节存储午夜（00:00:00.000）后的分钟数。</font></p>
<p><font size="1">例如，下面的代码演示了smalldatetime变量中，仅包含单纯的日期和单纯的时间时，日期存储的十六进制存储表示结果。</font></p>
<p><font face="Courier New" size="1">DECLARE @dt smalldatetime</font></p>
<p><font size="1"><font face="Courier New">--</font>单纯的日期</font></p>
<p><font face="Courier New" size="1">SET @dt='1900-1-2'</font></p>
<p><font face="Courier New" size="1">SELECT CAST(@dt as binary(4))</font></p>
<p><font size="1"><font face="Courier New">--</font>结果<font face="Courier New">: 0x00010000</font></font></p>
<p><font size="1"><font face="Courier New">--</font>单纯的时间</font></p>
<p><font face="Courier New" size="1">SET @dt='00:10'</font></p>
<p><font size="1"><font face="Courier New">SELECT CAST(@dt as binary(4))<br />
</font><font face="Courier New">--</font>结果<font face="Courier New">: 0x0000000A</font></font></p>
<h2><font face="宋体, MS Song" size="1">日期处理函数</font></h2>
<p><font size="1">日期由年、月、日、时等多个部分组成，它的处理相对复杂，因此，SQL Server提供了大量的日期处理函数，用以完成各种日期数据的处理。掌握好这些函数，对完成数据库的各种日期处理非常必要，本节将介绍几个常用的日期处理函数。期增减函数可以对日期指定部分的值进行增减，并返回处理后的日期值，SQL Server提供的日期增减函数为DATEADD。</font></p>
<p><br />
<font size="1">DATEADD</font><font size="1">的具体语法如下：<font face="Courier New">DATEADD ( datepart , number, date )</font></font></p>
<p><font size="1">其中包括以下参数。</font></p>
<p><font size="1">&#161;&nbsp;datepart：是规定应向日期的哪一部分返回新值的参数。表2-1列出了SQL Server支持的日期部分、缩写及含义。</font></p>
<p><font size="1"><font face="宋体, MS Song">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DATEADD</font>、<font face="宋体, MS Song">DATEDIFF</font>支持的日期部分、缩写及含义</font></p>
<table border="1" cellpadding="0" cellspacing="0" width="561">
    <tbody>
        <tr>
            <td valign="top" width="187">
            <p><font size="1">日期部分</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">缩<font face="宋体, MS Song">&nbsp;&nbsp;&nbsp; </font>写</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">含<font face="宋体, MS Song">&nbsp;&nbsp;&nbsp; </font>义</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="187">
            <p><font size="1">Year</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">yy , yyyy</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">年份</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="187">
            <p><font size="1">Quarter</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">qq , q</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">季度</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="187">
            <p><font size="1">Month</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">mm , m</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">月份</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="187">
            <p><font size="1">Dayofyear</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">dy,y</font></p>
            </td>
            <td rowspan="2" valign="top" width="187">
            <p><font size="1">日</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="187">
            <p><font size="1">Day</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">dd , d</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="187">
            <p><font size="1">Week</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">wk , ww</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">星期</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="187">
            <p><font size="1">Hour</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">Hh</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">小时</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="187">
            <p><font size="1">Minute</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">mi , n</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">分钟</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="187">
            <p><font size="1">Second</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">ss , s</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">秒</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="187">
            <p><font size="1">Millisecond</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">Ms</font></p>
            </td>
            <td valign="top" width="187">
            <p><font size="1">毫秒</font></p>
            </td>
        </tr>
    </tbody>
</table>
<p><font size="1">&#161;&nbsp;number：是用来增加datepart的值。正数表示增加，负数表示减少，如果指定的是非整数值，则忽略此值的小数部分，不做四舍五入处理。例如，DATEADD（Day,1.7,date），表示date增加1天。</font></p>
<p><font size="1">&#161;&nbsp;date：是返回datetime或smalldatetime值或日期格式字符串的表达式。</font></p>
<p><font size="1">如果date是smalldatetime，则返回smalldatetime，否则返回datetime。date为smalldatetime，Datepart为Second（ss,s）或Millisecond（ms）时，返回值将根据日期增减的结果调整到分钟；date为datetime，Datepart为Millisecond（ms）时，返回值将根据日期增减的结果调整为百分之三秒。调整规则可以参考2.1节的相关说明。</font></p>
<p><font size="1">date允许直接与number进行增减计算，即对于DATEADD（Day,number,date），等同于date+number。</font></p>
<h3><font face="宋体, MS Song"><font size="1">&nbsp;日期信息获取函数</font></font></h3>
<p><font size="1">日期信息获取函数用于获取日期指定部分的相关信息，常用的日期信息获取函数如表2-2所示。</font></p>
<p><font size="1"><font face="宋体, MS Song">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </font>常用的日期信息获取函数</font></p>
<table border="1" cellpadding="0" cellspacing="0" width="561">
    <tbody>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">功能说明</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">语<font face="宋体, MS Song">&nbsp;&nbsp;&nbsp; </font>法</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">参数及返回值数据类型说明</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">返回代表指定日期的指定日期部分的字符串</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">DATENAME(datepart,date)</font></p>
            </td>
            <td rowspan="2" width="253">
            <p><font size="1">datepart是指定应返回的日期部分的参数，其定义如表2-3所示。date是返回datetime或smalldatetime值或日期格式字符串的表达式。DATENAME函数返回nvarchar，DATEPART函数返回int</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">返回代表指定日期的指定日期部分的整数</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">DATEPART(datepart,date)</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">返回表示指定日期中的年份的整数</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">YEAR(date)</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">返回int</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">返回表示指定日期中的月份的整数</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">MONTH(date)</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">返回int</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">返回表示指定日期中的天的整数</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">DAY(date)</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">返回int</font></p>
            </td>
        </tr>
    </tbody>
</table>
<p><font size="1"><font face="宋体, MS Song">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DATENAME</font>、<font face="宋体, MS Song">DATEPART</font>支持的日期部分、缩写及含义</font></p>
<table border="1" cellpadding="0" cellspacing="0" width="561">
    <tbody>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">日期部分</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">缩<font face="宋体, MS Song">&nbsp;&nbsp;&nbsp; </font>写</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">含<font face="宋体, MS Song">&nbsp;&nbsp;&nbsp; </font>义</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">Year</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">yy , yyyy</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">年份</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">Quarter</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">qq , q</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">季度</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">Month</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">mm , m</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">月份</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">Dayofyear</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">dy , y</font></p>
            </td>
            <td rowspan="2" valign="top" width="253">
            <p><font size="1">日</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">Day</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">dd , d</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">Week</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">wk , ww</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">自年初开始的第几个星期</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">Weekday</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">Dw</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">星期几（例如星期一、星期二）</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">Hour</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">Hh</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">小时</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">Minute</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">mi , n</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">分钟</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">Second</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">ss , s</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">秒。date为smalldatetime时，始终返回0</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="140">
            <p><font size="1">Millisecond</font></p>
            </td>
            <td valign="top" width="168">
            <p><font size="1">Ms</font></p>
            </td>
            <td valign="top" width="253">
            <p><font size="1">毫秒。date为smalldatetime时，始终返回0，为datetime时，返回百份之三秒</font></p>
            </td>
        </tr>
    </tbody>
</table>
<p><font size="1">DATEPART（Week,date）返回的星期计算方式，是按照星期日为一周的第一天，这点与中国人的日期处理习惯不同，在使用时要注意这一点。DATENAME函数返回指定日期的指定日期部分的字符串，其返回的具体字符串值，与SET DATEFIRST及SET DATELANGUAGE选项的设置有关。使用DATEPART（Weekday,date）时，其返回的值与SET DATEFIRST选项的设置有关，具体的将在2.3节中说明。</font></p>
<h3><font face="宋体, MS Song"><font size="1">&nbsp;日期差值计算函数</font></font></h3>
<p><font size="1">日期差值计算函数用于计算两个给定日期指定部分的边界数，SQL Server提供的日期差值计算函数为DATEDIFF。</font></p>
<p><font size="1">DATEDIFF的具体语法如下：</font></p>
<p><font face="Courier New" size="1">DATEDIFF ( datepart , startdate , enddate ) </font></p>
<p><font size="1">其中包括以下参数。</font></p>
<p><font size="1">&#161;&nbsp;datepart：规定了应在日期的哪一部分计算差额，其定义如表2-1所示。</font></p>
<p><font size="1">&#161;&nbsp;startdate：规定了计算的开始日期。</font></p>
<p><font size="1">&#161;&nbsp;enddate：规定了计算的终止日期。</font></p>
<p><font size="1">返回类型：integer</font></p>
<p><font size="1">计算的开始日期和终止日期，可以是日期或日期格式的字符串。计算的方法是从enddate减去startdate。如果startdate比enddate晚，返回负值。当结果超出整数值范围，DATEDIFF就产生错误。对于毫秒，最大数是24天20小时31分钟23.647秒。对于秒，最大数是68年。</font></p>
<p><font size="1">计算跨分钟、秒和毫秒这些边界的方法，使得DATEDIFF给出的结果在全部数据类型中是一致的。结果是带正负号的整数值，其等于跨第一个和第二个日期间的datepart边界数。例如，在2005年1月4日和2005年2月11日之间的月份数是1。</font></p>
<h3><font face="宋体, MS Song"><font size="1">&nbsp;其他日期处理相关函数</font></font></h3>
<p><font size="1">其他常用的日期处理相关函数包括以下几个。</font></p>
<h4><font face="宋体, MS Song"><font size="1">1．GETDATE</font></font></h4>
<p><font size="1">GETDATE按照datetime值返回当前系统日期和时间。</font></p>
<p><font size="1">GETDATE的语法如下：</font></p>
<p><font face="Courier New" size="1">GETDATE()</font></p>
<p><font size="1">返回类型：datetime</font></p>
<h4><font face="宋体, MS Song"><font size="1">2．ISDATE</font></font></h4>
<p><font size="1">ISDATE确定输入的表达式是否有效日期。</font></p>
<p><font size="1">在输入日期表达式时，日期都是以日期格式的字符串提供的，由于不同的区域有不同的日期格式，所以并不能保证输入的日期表达式能够被SQL Server识别，这种情况下，就需要用ISDATE来判断日期表达式能否正确地被SQL Server识别了。</font></p>
<p><font size="1">ISDATE的语法如下：</font></p>
<p><font face="Courier New" size="1">ISDATE(expression)</font></p>
<p><font size="1">返回类型：int</font></p>
<h4><font face="宋体, MS Song"><font size="1">3．CONVERT</font></font></h4>
<p><font size="1">CONVERT将某种数据类型的表达式显式转换为另一种数据类型。</font></p>
<p><font size="1">严格来说，CONVERT不属于日期处理函数，只是它被经常用于日期处理中，所以这里把它列入了其他日期处理函数，下面是CONVERT的用法描述（只重点说明在日期处理中的应用）。</font></p>
<p><font size="1">CONVERT的具体语法如下：</font></p>
<p><font face="Courier New" size="1">CONVERT ( data_type [ ( length ) ] , expression [ , style ] )</font></p>
<p><font size="1">其中包括以下参数。</font></p>
<p><font size="1">&#161;&nbsp;expression：是要转换数据类型的有效SQL Server表达式。</font></p>
<p><font size="1">&#161;&nbsp;data_type：是expression转换后的数据类型，length是对于有精度定义需要的data_type的精度定义，对于没有精度定义需要的data_type，该参数可以省略。</font></p>
<p><font size="1">&#161;&nbsp;style：定义数据类型转换时的格式，对于日期类型的转换，它的定义如表2-4所示。</font></p>
<p><font size="1">表<font face="宋体, MS Song">2-4 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; style</font>在日期转换中的说明</font></p>
<table border="1" cellpadding="0" cellspacing="0" width="561">
    <tbody>
        <tr>
            <td valign="top" width="105">
            <p><font size="1">不带世纪数位</font></p>
            </td>
            <td valign="top" width="84">
            <p><font size="1">带世纪数位</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">标<font face="宋体, MS Song">&nbsp;&nbsp;&nbsp; </font>准</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">输入<font face="宋体, MS Song">/</font>输出</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">—</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">0或100</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">默认值</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">mon dd yyyy hh:miAM(或 PM)</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">1</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">101</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">美国</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">mm/dd/yyyy</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">2</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">102</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">ANSI</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">yy.mm.dd</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">3</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">103</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">英国/法国</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">dd/mm/yy</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">4</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">104</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">德国</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">dd.mm.yy</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">5</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">105</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">意大利</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">dd-mm-yy</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">6</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">106</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">—</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">dd mon yy</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">7</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">107</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">—</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">mon dd, yy</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">8</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">108</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">—</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">hh:mm:ss</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">—</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">9或109</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">默认值+毫秒</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">mon dd yyyy hh:mi:ss:mmmAM(或PM)</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">10</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">110</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">美国</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">mm-dd-yy</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">11</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">111</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">日本</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">yy/mm/dd</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">12</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">112</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">ISO</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">yymmdd</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">—</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">13或113</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">欧洲默认值+毫秒</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">dd mon yyyy hh:mm:ss:mmm(24h)</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">14</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">114</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">—</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">hh:mi:ss:mmm(24h)</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">—</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">20或120</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">ODBC规范</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">yyyy-mm-dd hh:mm:ss[.fff]</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">—</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">21或121</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">ODBC规范（带毫秒）</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">yyyy-mm-dd hh:mm:ss[.fff]</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">—</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">126</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">ISO8601</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">yyyy-mm-ddThh:mm:ss.mmm</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">—</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">130</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">Hijri</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">dd mon yyyy hh:mi:ss:mmmAM</font></p>
            </td>
        </tr>
        <tr>
            <td valign="top" width="105">
            <p align="center"><font size="1">—</font></p>
            </td>
            <td valign="top" width="84">
            <p align="center"><font size="1">131</font></p>
            </td>
            <td valign="top" width="141">
            <p><font size="1">Hijri</font></p>
            </td>
            <td valign="top" width="230">
            <p><font size="1">dd/mm/yy hh:mi:ss:mmmAM</font></p>
            </td>
        </tr>
    </tbody>
</table>
<div>
<p><font size="1">说明<font face="宋体, MS Song">：</font></font></p>
<p><font face="宋体, MS Song" size="1">①&nbsp;输入/输出：&#8220;输入&#8221;表示从字符串转换为日期时字符串的日期格式，&#8220;输出&#8221;指从日期转换为字符串时的日期字符串格式。</font></p>
<p><font face="宋体, MS Song" size="1">②&nbsp;Hijri：是具有几种变化形式的日历系统，SQL Server使用其中的科威特算法。</font></p>
</div>
<p><font size="1">当从smalldatetime转换为字符数据时，由于smalldatetimer只保存到分钟的数据，因此，对于包含秒或毫秒的样式，将在秒或毫秒的位置上显示零。当从datetime或smalldatetime值进行转换时，可以通过使用适当的char或varchar数据类型长度来截断不需要的日期部分。</font></p>
<div>
<p><font size="1">注意<font face="宋体, MS Song">：</font></font></p>
<p><font face="宋体, MS Song" size="1">在SQL Server中，由于直接提供的日期均是以日期格式的字符串提供，所以在使用CONVERT进行日期格式转换时，要先把日期格式的字符串转换为日期型，然后才能利用CONVERT进行日期格式转换，否则就变成字符串转换为字符串，此时的style选项是无效的。</font></p>
</div>
<p><font size="1">返回类型：由参数data_type确定。</font></p>
<p><font size="1">下面是利用CONVERT进行日期转换的简单示例：</font></p>
<p><font size="1"><font face="Courier New">/*== </font>字符转换为日期时<font face="Courier New">,Style</font>的使用<font face="Courier New"> ==*/</font></font></p>
<p><font size="1"><font face="Courier New">--1. Style=101</font>时<font face="Courier New">,</font>表示日期字符串为<font face="Courier New">:mm/dd/yyyy</font>格式</font></p>
<p><font face="Courier New" size="1">SELECT CONVERT(datetime,'11/1/2003',101)</font></p>
<p><font size="1"><font face="Courier New">--</font>结果<font face="Courier New">:2003-11-01 00:00:00.000</font></font></p>
<p><font size="1"><font face="Courier New">--2. Style=101</font>时<font face="Courier New">,</font>表示日期字符串为<font face="Courier New">:dd/mm/yyyy</font>格式</font></p>
<p><font face="Courier New" size="1">SELECT CONVERT(datetime,'11/1/2003',103)</font></p>
<p><font size="1"><font face="Courier New">--</font>结果<font face="Courier New">:2003-01-11 00:00:00.000</font><font face="Courier New">&nbsp;</font></font></p>
<p><font size="1"><font face="Courier New">/*== </font>日期转换为字符串<font face="Courier New"> ==*/</font></font></p>
<p><font face="Courier New" size="1">DECLARE @dt datetime</font></p>
<p><font face="Courier New" size="1">SET @dt='2003-1-11'</font></p>
<p><font size="1"><font face="Courier New">--1. Style=101</font>时<font face="Courier New">,</font>表示将日期转换为<font face="Courier New">:mm/dd/yyyy </font>格式</font></p>
<p><font face="Courier New" size="1">SELECT CONVERT(varchar,@dt,101)</font></p>
<p><font size="1"><font face="Courier New">--</font>结果<font face="Courier New">:01/11/2003</font></font></p>
<p><font size="1"><font face="Courier New">--2. Style=103</font>时<font face="Courier New">,</font>表示将日期转换为<font face="Courier New">:dd/mm/yyyy </font>格式</font></p>
<p><font face="Courier New" size="1">SELECT CONVERT(varchar,@dt,103)</font></p>
<p><font size="1"><font face="Courier New">--</font>结果<font face="Courier New">:11/01/2003</font></font></p>
<p><font size="1"><font face="Courier New">&nbsp;</font><font face="Courier New">/*== </font>这是很多人经常犯的错误<font face="Courier New">,</font>对非日期型转换使用日期的<font face="Courier New">style</font>样式<font face="Courier New"> ==*/</font></font></p>
<p><font face="Courier New" size="1">SELECT CONVERT(varchar,'2003-1-11',101)</font></p>
<font size="1"><font face="Courier New">--</font>结果</font><font face="Courier New" size="1">:2003-1-11</font>
<img src ="http://www.blogjava.net/sealyu/aggbug/212308.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2008-07-03 13:38 <a href="http://www.blogjava.net/sealyu/archive/2008/07/03/212308.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>SQL Server 2005 error: Connection Refused:connect</title><link>http://www.blogjava.net/sealyu/archive/2008/07/01/212000.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Tue, 01 Jul 2008 13:07:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2008/07/01/212000.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/212000.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2008/07/01/212000.html#Feedback</comments><slash:comments>4</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/212000.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/212000.html</trackback:ping><description><![CDATA[在安装了开发版的SQL Server2005 后，可以从Management Studio里面进行所有的操作，但是通过jdbc连接时出现错误：<br />
<font style="font-size: 14px;">Connection&nbsp;refused:&nbsp;connect<br />
经过几小时的挣扎，在配置管理器里面发现了问题，原来是TCPIP服务没有默认打开，解决如下：<br />
</font><font style="font-size: 14px;">1、打开SQL&nbsp;Server&nbsp;Configuration&nbsp;Manager&nbsp;-&gt;&nbsp;Protocols&nbsp;for&nbsp;SQLEXPRESS&nbsp;-&gt;&nbsp;TCP/IP<br />
2、右键单击启动TCP/IP<br />
3、双击进入属性，把IP地址中的IP&nbsp;all中的TCP端口设置为1433<br />
4、重新启动SQL&nbsp;Server&nbsp;2005服务</font><br />
<br />
<img src ="http://www.blogjava.net/sealyu/aggbug/212000.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2008-07-01 21:07 <a href="http://www.blogjava.net/sealyu/archive/2008/07/01/212000.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>sql server 中删除默认约束的通用sql脚本</title><link>http://www.blogjava.net/sealyu/archive/2008/04/17/193755.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Thu, 17 Apr 2008 06:31:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2008/04/17/193755.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/193755.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2008/04/17/193755.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/193755.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/193755.html</trackback:ping><description><![CDATA[作者： sealyu&nbsp;&nbsp; 日期：2008-04-17<br />
在SQL Server 中，如果给表的一个字段设置了默认值，就会在系统表sysobjects中生成一个默认约束。<br />
如果想删除这个设置了默认值的字段（假设此字段名column1），<br />
执行&#8220;ALTER TABLE table1 DROP COLUMN column1&#8221;时就会报错：<br />
The object 'DF__xxxxxxxxxxx' is dependent on column 'column1'. <br />
ALTER TABLE DROP COLUMN column1failed because one or more objects access this column.<br />
<br />
所以在删除此字段时需要先将系统表中的对应默认约束删除， 可以使用下面的脚本进行删除：<br />
-- this script drops the default constraint which is generated by the setting of default value.<br />
DECLARE @tablename VARCHAR(100), @columnname VARCHAR(100), @tab VARCHAR(100)<br />
SET @tablename='CountryGroupEmailAndWaitAux'<br />
SET @columnname='actionOfHasNoValidEmail'<br />
<br />
declare @defname varchar(100)<br />
declare @cmd varchar(100)<br />
<br />
select @defname = name<br />
FROM sysobjects so <br />
JOIN sysconstraints sc<br />
ON so.id = sc.constid<br />
WHERE object_name(so.parent_obj) = @tablename<br />
AND so.xtype = 'D'<br />
AND sc.colid =<br />
(SELECT colid FROM syscolumns<br />
WHERE id = object_id(@tablename) AND<br />
name = @columnname)<br />
<br />
select @cmd='alter table '+ @tablename+ ' drop constraint '+ @defname<br />
if @cmd is null print 'No default constraint to drop'<br />
exec (@cmd)<br />
<br />
在删除对应的默认约束后，执行：<br />
ALTER TABLE table1 DROP COLUMN column1<br />
即可删除字段。<br />
<img src ="http://www.blogjava.net/sealyu/aggbug/193755.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2008-04-17 14:31 <a href="http://www.blogjava.net/sealyu/archive/2008/04/17/193755.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>使用一条SQL语句删除表中重复记录（转载）</title><link>http://www.blogjava.net/sealyu/archive/2008/04/10/192010.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Thu, 10 Apr 2008 14:55:00 GMT</pubDate><guid>http://www.blogjava.net/sealyu/archive/2008/04/10/192010.html</guid><wfw:comment>http://www.blogjava.net/sealyu/comments/192010.html</wfw:comment><comments>http://www.blogjava.net/sealyu/archive/2008/04/10/192010.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/sealyu/comments/commentRss/192010.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/sealyu/services/trackbacks/192010.html</trackback:ping><description><![CDATA[<div>
<p>数据库结构的脚本:<br />
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TempA]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)<br />
drop table [dbo].[TempA]<br />
GO</p>
<p>CREATE TABLE [dbo].[TempA] (<br />
&nbsp;[id] [int] IDENTITY (1, 1) NOT NULL ,<br />
&nbsp;[PositionName] [varchar] (256) COLLATE Chinese_PRC_CI_AS NULL ,<br />
&nbsp;[EnglishPositionName] [varchar] (256) COLLATE Chinese_PRC_CI_AS NULL <br />
) ON [PRIMARY]<br />
GO</p>
<p>ALTER TABLE [dbo].[TempA] ADD <br />
&nbsp;CONSTRAINT [PK_TempA] PRIMARY KEY&nbsp; CLUSTERED <br />
&nbsp;(<br />
&nbsp;&nbsp;[id]<br />
&nbsp;)&nbsp; ON [PRIMARY] <br />
GO<br />
<br />
TempA表中有三个字段,id唯一且为主键,自动增长;&nbsp;PositionName,EnglishPositionName中有重复的记录,比如:<br />
id&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PositionName&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; EnglishPositionName<br />
20&nbsp;&nbsp;&nbsp;&nbsp; 其他&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Others<br />
21&nbsp;&nbsp;&nbsp;&nbsp; 质量工程师&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;QC Engineer <br />
22&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;其他&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Others<br />
.......<br />
100&nbsp; 质量工程师&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;QC Engineer <br />
需要剔除重复的"其他","质量工程师"等记录。</p>
<p>采用的SQL语句：<br />
Delete from TempA where id not in (<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; select max(t1.id) from TempA t1 group by<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; t1.PositionName,t1.EnglishPositionName)<br />
<br />
说明：<br />
(1)需要剔除那几个用于判断重复的字段，则将它们放在group by语句之后。<br />
(2)max(t1.id) 也可以改成：min(t1.id) </p>
</div>
<img src ="http://www.blogjava.net/sealyu/aggbug/192010.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/sealyu/" target="_blank">seal</a> 2008-04-10 22:55 <a href="http://www.blogjava.net/sealyu/archive/2008/04/10/192010.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>