??xml version="1.0" encoding="utf-8" standalone="yes"?>怡红院av在线,国产精品欧美极品,国产精品一区毛片http://www.aygfsteel.com/sealyu/archive/2010/11/29/339341.htmlsealsealMon, 29 Nov 2010 10:49:00 GMThttp://www.aygfsteel.com/sealyu/archive/2010/11/29/339341.htmlhttp://www.aygfsteel.com/sealyu/comments/339341.htmlhttp://www.aygfsteel.com/sealyu/archive/2010/11/29/339341.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/339341.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/339341.htmlI 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 “national”. That is be either nchar, nvarchar or ntext.

Ms SQL Server 2005 seems to go one step further by announcing future deprecation for ntext, text and image types.

From Sql Server 2005 notes:

ntext, text, and image 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 nvarchar(max), varchar(max), and varbinary(max) instead.”

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.

/**
* Unicode support in SQL Server
*
* @author icocan
*/
public class UnicodeSQLServerDialect extends SQLServerDialect {

public UnicodeSQLServerDialect() {
super();

// Use Unicode Characters
registerColumnType(Types.VARCHAR, 255, "nvarchar($l)");
registerColumnType(Types.CHAR, "nchar(1)");
registerColumnType(Types.CLOB, "nvarchar(max)");

// Microsoft SQL Server 2000 supports bigint and bit
registerColumnType(Types.BIGINT, "bigint");
registerColumnType(Types.BIT, "bit");
}
}
read more ...

You have to write your own SQLServerDialect class, it looks something like this:
publicclassSQLServerNativeDialectextendsSQLServerDialect{
     publicSQLServerNativeDialect(){
         super();
         registerColumnType(Types.VARCHAR,"nvarchar($l)");
         registerColumnType(Types.CLOB,"nvarchar(max)");
     }

    publicString getTypeName(int code,int length,int precision,int scale)throwsHibernateException{
        if(code !=2005){
            returnsuper.getTypeName(code, length, precision, scale);
        }else{
            return"ntext";
        }
    }
}

This class maps Hibernate's types to SQL types, so the class will map the nvarchar(max) SQL Data Type to Hibernate's CLOB data type.

The getTypeName 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).

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.




seal 2010-11-29 18:49 发表评论
]]>
nvarchar与varchar的区?/title><link>http://www.aygfsteel.com/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.aygfsteel.com/sealyu/archive/2010/11/29/339293.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/339293.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2010/11/29/339293.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/339293.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/sealyu/services/trackbacks/339293.html</trackback:ping><description><![CDATA[<p>nvarchar与varchar的区?/p> <p>varchar[(n)]   <br />   长度?  n   个字节的可变长度且非   Unicode   的字W数据。n   必须是一个介?  1   ?  8,000   之间的数倹{存储大ؓ(f)输入数据的字节的实际长度Q而不?  n   个字节。所输入的数据字W长度可以ؓ(f)零。varchar   ?  SQL-92   中的同义词ؓ(f)   char   varying   ?  character   varying?  <br />     <br />   nvarchar(n)   <br />   包含   n   个字W的可变长度   Unicode   字符数据。n   的值必M?  1   ?  4,000   之间。字节的存储大小是所输入字符个数的两倍。所输入的数据字W长度可以ؓ(f)零。nvarchar   ?  SQL-92   中的同义词ؓ(f)   national   char   varying   ?  national   character   varying?nbsp;  </p> <p>通俗一點就是varchar適合輸入英文和數字,nvarchar一般用做中文或其它語言的入,這樣到別的語pM會出現亂?))</p> <img src ="http://www.aygfsteel.com/sealyu/aggbug/339293.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2010-11-29 10:51 <a href="http://www.aygfsteel.com/sealyu/archive/2010/11/29/339293.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>sql server 判断?视图/存储q程是否存在Q{Q?/title><link>http://www.aygfsteel.com/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.aygfsteel.com/sealyu/archive/2010/05/28/322100.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/322100.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2010/05/28/322100.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/322100.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/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>--如果是(f)时表可以?说明,如果用查扑֮表方法来打(f)时表?x)找不?发布区别对代.)<br /> if object_id('tempdb..##temp') is not null<br />    drop table ##temp</p> <p>--判断存储q程是否存在<br /> if exists(select 1 from sysobjects where id=object_id('所有?存储q程?) and xtype='P')   <br /> print '存在'   <br /> else   <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,      --object 名称 <br /> id   int,          --object id <br /> xtype char(2),     -- object cd   <br /> type char(2),     -- Object cdQ与xtype g一模一P 有点郁闷…Q? <br /> uid   smallint,     -- object 所有者的ID <br /> ...                --其他的字D不常用到?nbsp;  <br /> )</p> <p>sysobjects的xtype 代表的对象类型。可以是下列对象cd中的一U:(x) <br /> C = CHECK U束 <br /> D = 默认值或 DEFAULT U束 <br /> F = FOREIGN KEY U束 <br /> L = 日志 <br /> FN = 标量函数 <br /> IF = 内嵌表函?<br /> P = 存储q程 <br /> PK = PRIMARY KEY U束Q类型是 KQ?<br /> RF = 复制{选存储过E?<br /> S = pȝ?<br /> TF = 表函?<br /> TR = 触发?<br /> U = 用户?<br /> UQ = UNIQUE U束Q类型是 KQ?<br /> V = 视图 <br /> X = 扩展存储q程 </p> <p><br /> object_id和data_object_id都是表示数据库对象的唯一标志?br /> <br /> object_id是数据库对象的逻辑idQdata_object_id是数据库对象的物理id?br /> <br /> 如果一些object没有物理属性的话那它就不存在data_object_idQ例如procedure,function,package,data type,db link,mv定义Qview定义Q(f)时表Q分定义{等q些object都是没有对应着某个segmentQ因此它们的data_object_id 都ؓ(f)I?br /> <br /> 当一个表建立的时候,他的object_id ? data_object_id是相{的。当表move和truncate后data_object_id?x)发生变化。修改表l构不会(x)更改?br /> <br /> select object_id,data_object_id from user_objects where object_name=’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=’T’ AND OWNER=’TEST’;<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.aygfsteel.com/sealyu/aggbug/322100.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2010-05-28 02:40 <a href="http://www.aygfsteel.com/sealyu/archive/2010/05/28/322100.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>MySQLdb User's Guidehttp://www.aygfsteel.com/sealyu/archive/2010/05/17/321217.htmlsealsealMon, 17 May 2010 15:56:00 GMThttp://www.aygfsteel.com/sealyu/archive/2010/05/17/321217.htmlhttp://www.aygfsteel.com/sealyu/comments/321217.htmlhttp://www.aygfsteel.com/sealyu/archive/2010/05/17/321217.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/321217.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/321217.html

Contents

Introduction

MySQLdb is an thread-compatible interface to the popular MySQL database server that provides the Python database API.

Installation

The README file has complete installation instructions.

_mysql

If you want to write applications which are portable across databases, use MySQLdb, and avoid using this module directly. _mysql provides an interface which mostly implements the MySQL C API. For more information, see the MySQL documentation. 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.

MySQL C API translation

The MySQL C API has been wrapped in an object-oriented way. The only MySQL data structures which are implemented are the MYSQL (database connection handle) and MYSQL_RES (result handle) types. In general, any function which takes MYSQL *mysql as an argument is now a method of the connection object, and any function which takes MYSQL_RES *result 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 mysql_ prefix is dropped from the name. Most of the conn methods listed are also available as MySQLdb Connection object methods. Their use is non-portable.

MySQL C API function mapping

C API _mysql
mysql_affected_rows() conn.affected_rows()
mysql_autocommit() conn.autocommit()
mysql_character_set_name() conn.character_set_name()
mysql_close() conn.close()
mysql_commit() conn.commit()
mysql_connect() _mysql.connect()
mysql_data_seek() result.data_seek()
mysql_debug() _mysql.debug()
mysql_dump_debug_info conn.dump_debug_info()
mysql_escape_string() _mysql.escape_string()
mysql_fetch_row() result.fetch_row()
mysql_get_character_set_info() conn.get_character_set_info()
mysql_get_client_info() _mysql.get_client_info()
mysql_get_host_info() conn.get_host_info()
mysql_get_proto_info() conn.get_proto_info()
mysql_get_server_info() conn.get_server_info()
mysql_info() conn.info()
mysql_insert_id() conn.insert_id()
mysql_num_fields() result.num_fields()
mysql_num_rows() result.num_rows()
mysql_options() various options to _mysql.connect()
mysql_ping() conn.ping()
mysql_query() conn.query()
mysql_real_connect() _mysql.connect()
mysql_real_query() conn.query()
mysql_real_escape_string() conn.escape_string()
mysql_rollback() conn.rollback()
mysql_row_seek() result.row_seek()
mysql_row_tell() result.row_tell()
mysql_select_db() conn.select_db()
mysql_set_character_set() conn.set_character_set()
mysql_ssl_set() ssl option to _mysql.connect()
mysql_stat() conn.stat()
mysql_store_result() conn.store_result()
mysql_thread_id() conn.thread_id()
mysql_thread_safe_client() conn.thread_safe_client()
mysql_use_result() conn.use_result()
mysql_warning_count() conn.warning_count()
CLIENT_* MySQLdb.constants.CLIENT.*
CR_* MySQLdb.constants.CR.*
ER_* MySQLdb.constants.ER.*
FIELD_TYPE_* MySQLdb.constants.FIELD_TYPE.*
FLAG_* MySQLdb.constants.FLAG.*

Some _mysql examples

Okay, so you want to use _mysql anyway. Here are some examples.

The simplest possible database connection is:

import _mysql
db=_mysql.connect()

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 USE a database. Chances are you need to supply more information.:

db=_mysql.connect("localhost","joebob","moonpie","thangs")

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".

We haven't even begun to touch upon all the parameters connect() can take. For this reason, I prefer to use keyword parameters:

db=_mysql.connect(host="localhost",user="joebob",
passwd="moonpie",db="thangs")

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:

db=_mysql.connect(passwd="moonpie",db="thangs")

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):

db=_mysql.connect(host="outhouse",port=3307,passwd="moonpie",db="thangs")

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.

Generally speaking, putting passwords in your code is not such a good idea:

db=_mysql.connect(host="outhouse",db="thangs",read_default_file="~/.my.cnf")

This does what the previous example does, but gets the username and password and other parameters from ~/.my.cnf (UNIX-like systems). Read about option files for more details.

So now you have an open connection as db 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 db.query():

db.query("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < 5""")

There's no return value from this, but exceptions can be raised. The exceptions are defined in a separate module, _mysql_exceptions, but _mysql exports them. Read DB API specification PEP-249 to find out what they are, or you can use the catch-all MySQLError.

At this point your query has been executed and you need to get the results. You have two options:

r=db.store_result()
# ...or...
r=db.use_result()

Both methods return a result object. What's the difference? store_result() 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 LIMIT clause to your query, to limit the number of rows returned. The other is to use use_result(), 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 all the rows. Generally I recommend using store_result() unless your result set is really huge and you can't use LIMIT for some reason.

Now, for actually getting real results:

>>> r.fetch_row()
(('3','2','0'),)

This might look a little odd. The first thing you should know is, fetch_row() takes some additional parameters. The first one is, how many rows (maxrows) should be returned. By default, it returns one row. It may return fewer rows than you asked for, but never more. If you set maxrows=0, it returns all rows of the result set. If you ever get an empty tuple back, you ran out of rows.

The second parameter (how) tells it how the row should be represented. By default, it is zero which means, return as a tuple. how=1 means, return it as a dictionary, where the keys are the column names, or table.column if there are two columns with the same name (say, from a join). how=2 means the same as how=1 except that the keys are always table.column; this is for compatibility with the old Mysqldb module.

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 maxrows.

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, _mysql can do this for you. (And MySQLdb does do this for you.) To have automatic type conversion done, you need to create a type converter dictionary, and pass this to connect() as the conv keyword parameter.

The keys of conv should be MySQL column types, which in the C API are FIELD_TYPE_*. You can get these values like this:

from MySQLdb.constants import FIELD_TYPE

By default, any column type that can't be found in conv is returned as a string, which works for a lot of stuff. For our purposes, we probably want this:

my_conv = { FIELD_TYPE.LONG: int }

This means, if it's a FIELD_TYPE_LONG, call the builtin int() function on it. Note that FIELD_TYPE_LONG is an INTEGER column, which corresponds to a C long, which is also the type used for a normal Python integer. But beware: If it's really an UNSIGNED INTEGER column, this could cause overflows. For this reason, MySQLdb actually uses long() to do the conversion. But we'll ignore this potential problem for now.

Then if you use db=_mysql.connect(conv=my_conv...), the results will come back ((3, 2, 0),), which is what you would expect.

MySQLdb

MySQLdb is a thin Python wrapper around _mysql 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 _mysql for the sake of efficiency.

The DB API specification PEP-249 should be your primary guide for using this module. Only deviations from the spec and other database-dependent things will be documented here.

Functions and attributes

Only a few top-level functions and attributes are defined within MySQLdb.

connect(parameters...)

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 mysql_options() 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:

host
name of host to connect to. Default: use the local host via a UNIX socket (where applicable)
user
user to authenticate as. Default: current effective user.
passwd
password to authenticate with. Default: no password.
db
database to use. Default: no default database.
port
TCP port of MySQL server. Default: standard port (3306).
unix_socket
location of UNIX socket. Default: use default location or TCP for remote hosts.
conv
type conversion dictionary. Default: a copy of MySQLdb.converters.conversions
compress
Enable protocol compression. Default: no compression.
connect_timeout
Abort if connect is not completed within given number of seconds. Default: no timeout (?)
named_pipe
Use a named pipe (Windows). Default: don't.
init_command
Initial command to issue to server upon connection. Default: Nothing.
read_default_file
MySQL configuration file to read; see the MySQL documentation for mysql_options().
read_default_group
Default group to read; see the MySQL documentation for mysql_options().
cursorclass
cursor class that cursor() uses, unless overridden. Default: MySQLdb.cursors.Cursor. This must be a keyword parameter.
use_unicode

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.

If False, text-like columns are returned as normal strings, but you can always write Unicode strings.

This must be a keyword parameter.

charset

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.

If not present, the default character set is used.

This must be a keyword parameter.

sql_mode

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.

If not present, the session SQL mode will be unchanged.

This must be a keyword parameter.

ssl
This parameter takes a dictionary or mapping, where the keys are parameter names used by the mysql_ssl_set 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. This must be a keyword parameter.
apilevel
String constant stating the supported DB API level. '2.0'
threadsafety

Integer constant stating the level of thread safety the interface supports. This is set to 1, which means: Threads may share the module.

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 mysql_store_result()), it is complicated by SSCursor (which uses mysql_use_result(); 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 COMMIT or ROLLBACK 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.

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.

For threaded applications, try using a connection pool. This can be done using the Pool module.

charset
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.
paramstyle

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.

Note that any literal percent signs in the query string passed to execute() must be escaped, i.e. %%.

Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc.

conv

A dictionary or mapping which controls how types are converted from MySQL to Python and vice versa.

If the key is a MySQL type (from FIELD_TYPE.*), then the value can be either:

  • a callable object which takes a string argument (the MySQL value),' returning a Python value
  • a sequence of 2-tuples, where the first value is a combination of flags from MySQLdb.constants.FLAG, 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.

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.

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 MySQLdb.converters.conversions. Several non-standard types are returned as strings, which is how MySQL returns all columns. For more details, see the built-in module documentation.

Connection Objects

Connection objects are returned by the connect() function.

commit()
If the database and the tables support transactions, this commits the current transaction; otherwise this method successfully does nothing.
rollback()
If the database and tables support transactions, this rolls back (cancels) the current transaction; otherwise a NotSupportedError is raised.
cursor([cursorclass])
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 Cursor class. Also see the additional supplied cursor classes in the usage section.

There are many more methods defined on the connection object which are MySQL-specific. For more information on them, consult the internal documentation using pydoc.

Cursor Objects

callproc(procname, args)

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.

Compatibility note: PEP-249 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.

The parameters are stored in the server as @_*procname*_*n*, where n 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.

Compatibility note: 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.

close()
Closes the cursor. Future operations raise ProgrammingError. 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.
info()
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 mysql_info(), and the Python warning module. (Non-standard)
setinputsizes()
Does nothing, successfully.
setoutputsizes()
Does nothing, successfully.
nextset()

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.

Note that MySQL doesn't support multiple result sets until 4.1.

Some examples

The connect() method works nearly the same as with _mysql:

import MySQLdb
db=MySQLdb.connect(passwd="moonpie",db="thangs")

To perform a query, you first need a cursor, and then you can execute queries on it:

c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s""", (max_price,))

In this example, max_price=5 Why, then, use %s 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 < 5".

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.

And now, the results:

>>> c.fetchone()
(3L, 2L, 0L)

Quite unlike the _mysql 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?

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.

If you wanted more rows, you could use c.fetchmany(n) or c.fetchall(). These do exactly what you think they do. On c.fetchmany(n), the n is optional and defaults to c.arraysize, 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.

Note that in contrast to the above, c.fetchone() returns None when there are no more rows to fetch.

The only other method you are very likely to use is when you have to do a multi-row insert:

c.executemany(
"""INSERT INTO breakfast (name, spam, eggs, sausage, price)
VALUES (%s, %s, %s, %s, %s)""",
[
("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
] )

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 %s. And also note that we only included format strings for one row. MySQLdb picks those out and duplicates them for each row.

Using and extending

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 connect() are completely implementation-dependent.

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.

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:

BaseCursor
The base class for Cursor objects. This does not raise Warnings.
CursorStoreResultMixIn
Causes the Cursor to use the mysql_store_result() function to get the query result. The entire result set is stored on the client side.
CursorUseResultMixIn
Causes the cursor to use the mysql_use_result() function to get the query result. The result set is stored on the server side and is transferred row by row using fetch operations.
CursorTupleRowsMixIn
Causes the cursor to return rows as a tuple of the column values.

CursorDictRowsMixIn

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 table.column. This can be avoided by using the SQL AS keyword. (This is yet-another reason not to use * in SQL queries, particularly where JOIN is involved.)
Cursor
The default cursor class. This class is composed of CursorWarningMixIn, CursorStoreResultMixIn, CursorTupleRowsMixIn, and BaseCursor, i.e. it raises Warning, uses mysql_store_result(), and returns rows as tuples.
DictCursor
Like Cursor except it returns rows as dictionaries.
SSCursor
A "server-side" cursor. Like Cursor but uses CursorUseResultMixIn. Use only if you are dealing with potentially large result sets.
SSDictCursor
Like SSCursor except it returns rows as dictionaries.

Embedded Server

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.

If you have built MySQLdb with embedded server support, there are two additional functions you will need to make use of:

server_init(args, groups)

Initialize embedded server. If this client is not linked against the embedded server library, this function does nothing.

args
sequence of command-line arguments
groups
sequence of groups to use in defaults files
server_end()
Shut down embedded server. If not using an embedded server, this does nothing.

See the MySQL documentation for more information on the embedded server.

Title: MySQLdb: a Python interface for MySQL
Author: Andy Dustman
Version: $Revision: 421 $


seal 2010-05-17 23:56 发表评论
]]>
如何在Mac OS Xpȝ中启用MySQL(?http://www.aygfsteel.com/sealyu/archive/2010/05/16/321082.htmlsealsealSun, 16 May 2010 01:38:00 GMThttp://www.aygfsteel.com/sealyu/archive/2010/05/16/321082.htmlhttp://www.aygfsteel.com/sealyu/comments/321082.htmlhttp://www.aygfsteel.com/sealyu/archive/2010/05/16/321082.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/321082.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/321082.html随着|络日益发展q有os x用户的增多,有可能会(x)需要在自己的xpȝ中运行mysql+php环境Q比如架讄站或者测试之cR简单步骤如下:(x)

  1、下载MySQL 5.x 发行?Q解压ƈ安装映像中的两个安装包文件?/p>

  a. mysql-5.x-osx10.6_x86_64.pkg Qmysql 5.x 标准版安?/p>

  b. MySQLStartupItem.pkgQmysql启动目Q可以上你的?sh)脑在启动系l时自动q行mysql服务。它安装?Library /StartupItems/MySQL/Q如果你不想pȝ启动时运行mysql服务Q请不要安装。如果你在安装后又不想用,请删?Library /StartupItems/MySQL/q个目录?/p>

  启动mysqlQ?/p>

  2、如果你已经安装?jin)MySQLStartupItem.pkgQ重新启动电(sh)脑即可?/p>

  3、如果你有安装MySQLStartupItem.pkg或者不惛_动电(sh)脑,q行Q应用程序-实用E序Q终端程序,在终端中输入命o(h)Q?/p>

  sudo /Library/StartupItems/MySQL/MySQL start

  然后输入你的pȝ理员密码,如果没有讑֮密码q接回车?/p>

  关闭mysql服务Q?/p>

  l端中输入命令:(x)sudo /Library/StartupItems/MySQL/MySQL stop

  然后输入你的pȝ理员密码,如果没有讑֮密码q接回车?/p>

  mysql root账户密码Q?/p>

  mysql root密码初始值是I。这栯然没有问题。但很不安全。徏议你更改root用户密码。注意:(x)mysql root用户和系l中的root用户是不一L(fng)。是完全两个不同的用戗?/p>

  更改mysql root密码请在l端中输入命令:(x)

  /usr/local/mysql/bin/mysqladmin -u root password 新密?/p>

  同时你也可以随时使用q条命o(h)更改你的密码?/p>

  4、下载x版mysql数据库管理工?/p>

  q是一个运行在mac os xpȝ中的mysql数据库管理YӞ支持本地?qing)远E数据库理。ƈ且还是免费的。这个程序的优点是完全CGI界面。ƈ且密码是保存在本Z的。相Ҏ(gu)? 安全?/p>

seal 2010-05-16 09:38 发表评论
]]>
Software caused connection abort: recv failedhttp://www.aygfsteel.com/sealyu/archive/2010/04/15/318384.htmlsealsealWed, 14 Apr 2010 21:58:00 GMThttp://www.aygfsteel.com/sealyu/archive/2010/04/15/318384.htmlhttp://www.aygfsteel.com/sealyu/comments/318384.htmlhttp://www.aygfsteel.com/sealyu/archive/2010/04/15/318384.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/318384.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/318384.html
Solution: Uninstall ipv6 from Network management.

seal 2010-04-15 05:58 发表评论
]]>
数据库的动态字D问?/title><link>http://www.aygfsteel.com/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.aygfsteel.com/sealyu/archive/2010/03/18/315797.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/315797.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2010/03/18/315797.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/315797.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/sealyu/services/trackbacks/315797.html</trackback:ping><description><![CDATA[<div>Sealyu  2010Q?Q?8</div> <div><br /> </div> 在项目中l常?x)碰到这L(fng)问题Q?用户要求他们的品等实体的属性是可定制的。比如:(x)产品的数量、高度、重量等属性,都是可以在后台增删该查的。在q种情况下,使用java建立实体遇到问题(sh)(jin)Q因为数据库中的字段是不定的?q种情况在一些单据、试L(fng)地方是很常见的? <div>1。目前ؓ(f)止,没有发现比较完美的解x(chng)法?之前目中遇C(jin)一ơ动态生成单据的情况Q主要是通过使用几张表来存储表的l构和字D信息来实现?q种情况下,实现查询和报表等功能时就?x)受到?jing)响?具体Ҏ(gu)跟下面这位的cMQ? </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; ">我在l一家打字公司开发一个将表单的内容输入数据库的程序。表单中可能有简单的送货收据Q?0多个字段Q,可能有民意调查的表格Q?0多个字段Q,可能有保险公司的用户登记表(100多个字段Q。讨厌的是这L(fng)表单可能又几癄?nbsp;  <br />       我设计的数据库如下:(x)   <br />       表单的种c表Q表1Q:(x)   <br />       Form_ID           //表单的种cID   <br />       Form_Name       //表单的名U?nbsp;  <br />     <br />       某一个表单的字段表(?Q?nbsp;  <br />       Field_ID           //字段的ID   <br />       Field_Name       //字段的名U?nbsp;  <br />       Form_ID             //表单的种cIDQ与?q接   <br />     <br />       具体的某一个表单表Q表3Q?nbsp;  <br />       Sheet_ID                     //具体的某一个表单的ID   <br />       Client_ID                   //q个表单所属的客户IDQ与客户表连?nbsp;  <br />     <br />       某一个表单的字段内容表(?Q?nbsp;  <br />       Field_Value_ID         //字段的内容ID   <br />       Field_Value               //字段的内?nbsp;  <br />       Field_ID                     //字段的IDQ与?q接   <br />       Sheet_ID                     //具体的某一个表单的IDQ与?q接   <br />     <br />       每增加了(jin)一U新的表单时Q在?和表2中添加如下记录:(x)   <br />           ?QForm_ID           Form_Name   <br />                       A001                 送货?nbsp;    <br />           ?QField_ID         Field_Name       Form_ID             <br />                       f0001               发货日期           A001     <br />                       f0002               发货?nbsp;              A001     <br />                       f0003             收货人地址         A001     <br />       q样Q当某一个打字公司的客户要求输入q个“送货?#8221;Ӟ每输入一个送货单(卌单表3Q,?和表4d如下记录Q(每输入一个送货单之cȝ表单Q表3和表4都添加数据)(j)   <br />           ?QSheet_ID         Client_ID   <br />                       S001                 0000001   <br />           ?QField_Value_ID         Field_Value         Field_ID           Sheet_ID   <br />                           V0001                         2001.5.8               f0001                 S001     <br />                           V0002                             张三                     f0002               S001     <br />                           V0003                     大连?jng)西岗?nbsp;            f0003                 S001     <br />       打字公司Ҏ(gu)具体的某一个表单的IDQSheet_IDQ,l合4个表提取客户ID、表单种cdU、字D名U和字段内容存入另外的数据库?  </span></div> </div> <div>2。还看到q一U情况,是只用一个长字符串字D,利用xml的格式来存储对应的结构,同时在java中用xml2db{工h解析。这U情况下Q查询和报表功能同样不好实现。同Ӟxml节点的增删该查也不太方便?/div> <div>3。最后一U方法,是直接用数据库来实现。前几天看到DB2 9中已l支持对XML格式数据的存储和查询。用XQUERY来配套实现查询。不q这U方法对数据库的依赖性强Q目前ؓ(f)止,q没发现有其他数据库提供q种功能?/div> <div><br /> </div> <img src ="http://www.aygfsteel.com/sealyu/aggbug/315797.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2010-03-18 15:59 <a href="http://www.aygfsteel.com/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 DB2http://www.aygfsteel.com/sealyu/archive/2010/02/24/313810.htmlsealsealWed, 24 Feb 2010 08:43:00 GMThttp://www.aygfsteel.com/sealyu/archive/2010/02/24/313810.htmlhttp://www.aygfsteel.com/sealyu/comments/313810.htmlhttp://www.aygfsteel.com/sealyu/archive/2010/02/24/313810.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/313810.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/313810.html阅读全文

seal 2010-02-24 16:43 发表评论
]]>
spring的DriverManagerDataSource与apache的BasicDataSourceQ{Q?/title><link>http://www.aygfsteel.com/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.aygfsteel.com/sealyu/archive/2010/02/02/311728.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/311728.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2010/02/02/311728.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/311728.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/sealyu/services/trackbacks/311728.html</trackback:ping><description><![CDATA[情况是这L(fng)。。? <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 /> 重新启动服务器之后,问题?sh)然存在? <br /> 分析得出以下可能情况 <br /> 1.q接数达C(jin)150的最大上? <br /> 2.服务器端响应用户h的时间过长导? <br /> 3.q接池的配置数出?jin)问? <br /> <br /> 分析Q? <br /> 1.1个用戯问是OK的,当用2个用户对localhostq行讉KQ所以根本不可能辑ֈq发讉KU程?50的上限,所以应该不是数据库的原?排除?jin)第一U可? <br /> 2.之前讉K的JSP已经l过多次讉KQ所以不可能是第一ơ访问编译,q行而导致的h旉q长的原因,W二情况也否定? <br /> <br /> <strong>到此Q经q分析可以确定的是连接池Z(jin)问题...</strong> <br /> <br /> 首先?个知识点需要再弄的更清楚一? <br /> <br /> <strong>DriverManager与DataSource  q接数据库有何区?</strong> <br />         DriverManager传统的jdbcq接Q通过Class.forName("XXX"),的办法注册之后,可以DriverManager.getConnection()获得q接?jin)? <br /> <br />         DataSource是徏立在JNDI服务基础上的,需要application server配置datasource.首先需要注册一个DataSource(一般在/META-INF/context.xml?然后? web.xml文g中引用这个DataSource,可以DataSource.getConnection()获得q接,具体操作参?tomcat 目录里的JNDI Resources节) <br /> <br /> <strong>DataSource ?DBCP pool(q接? 的区别?</strong> <br />         J2EE 服务器启动时?x)徏立一定数量的池连接,q一直维持不于此数目的池连接。客L(fng)E序需要连接时Q池驱动E序?x)返回一个未使用的池q接q将其表Cؓ(f)忙。如? 当前没有I闲q接Q池驱动E序新Z定数量的q接Q新接的数量有配|参数决定。当使用的池q接调用完成后,池驱动程序将此连接表Cؓ(f)I闲Q其他调? 可以用这个连接? <br /> 相当于是优化?jin)DataSource的一U工? <br /> <br /> 跟数据库q接的部分是通过Spring的DataSource JDBCq接?配置的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><bean id="propertyConfigurer"   </li> <li>class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  </li> <li><!--PropertyPlaceholderConfigurercLdxxx.properties配置文g信息,以key和value的Ş?->  </li> <li><property name="locations">  </li> <li>    <list>  </li> <li>        <value>  </li> <li>          /WEB-INF/classes/config/pkm/environment/jdbc.properties  </li> <li>        </value>  </li> <li>        <value>  </li> <li>          <!--多个xxx.properties文g-->  </li> <li>        </value>  </li> <li>    </list>  </li> <li></property>  </li> <li></bean>  </li> <li>  </li> <li><!--事实上是因ؓ(f)DriverManagerDataSource建立q接是只要有q接新Z个connection,Ҏ(gu)没有q接池的作用-->  </li> <li><!--两种不同的DataSource-->  </li> <li><!--单纯的DataSource-->  </li> <li><bean id="pkmDataSource"   </li> <li>class="org.springframework.jdbc.datasource.DriverManagerDataSource">  </li> <li>    <property name="driverClassName">  </li> <li>        <value>${pkm.jdbc.driverClassName}</value>  </li> <li>        <!--${pkm.jdbc.driverClassName}是jdbc.properties文g 中的key-->  </li> <li>    </property>  </li> <li>    <property name="url">  </li> <li>        <value>${pkm.jdbc.url}</value>  </li> <li>    </property>  </li> <li>    <property name="username">  </li> <li>        <value>${pkm.jdbc.username}</value>  </li> <li>    </property>  </li> <li>    <property name="password">  </li> <li>        <value>${pkm.jdbc.password}</value>  </li> <li>    </property>  </li> <li></bean>  </li> <li>  </li> <li><!--q接?->  </li> <li><bean id="pkmDataSource"   </li> <li>class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" lazy-init="false">  </li> <li>    <property name="driverClassName" value="${pkm.jdbc.driverClassName}"/>  </li> <li>    <property name="url" value="${pkm.jdbc.url}"/>  </li> <li>    <property name="username" value="${pkm.jdbc.username}"/>  </li> <li>    <property name="password" value="${pkm.jdbc.password}"/>  </li> <li>    <property name="initialSize" value="5"/>  </li> <li>    <property name="maxActive" value="10"/>  </li> <li>    <property name="maxWait" value="60000"/>  </li> <li>    <property name="poolPreparedStatements" value="true"/>    </li> <li></bean>  </li> </ol> </div> <pre style="display: none;" name="code" class="xml"><bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <!--PropertyPlaceholderConfigurercLdxxx.properties配置文g信息,以key和value的Ş?-> <property name="locations"> <list> <value> /WEB-INF/classes/config/pkm/environment/jdbc.properties </value> <value> <!--多个xxx.properties文g--> </value> </list> </property> </bean> <!--事实上是因ؓ(f)DriverManagerDataSource建立q接是只要有q接新Z个connection,Ҏ(gu)没有q接池的作用--> <!--两种不同的DataSource--> <!--单纯的DataSource--> <bean id="pkmDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${pkm.jdbc.driverClassName}</value> <!--${pkm.jdbc.driverClassName}是jdbc.properties文g 中的key--> </property> <property name="url"> <value>${pkm.jdbc.url}</value> </property> <property name="username"> <value>${pkm.jdbc.username}</value> </property> <property name="password"> <value>${pkm.jdbc.password}</value> </property> </bean> <!--q接?-> <bean id="pkmDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" lazy-init="false"> <property name="driverClassName" value="${pkm.jdbc.driverClassName}"/> <property name="url" value="${pkm.jdbc.url}"/> <property name="username" value="${pkm.jdbc.username}"/> <property name="password" value="${pkm.jdbc.password}"/> <property name="initialSize" value="5"/> <property name="maxActive" value="10"/> <property name="maxWait" value="60000"/> <property name="poolPreparedStatements" value="true"/> </bean></pre> <br /> <br />         所以问题就出在q里,当用BasicDataSource后问题(sh)在出?所以是q接数量造成?在访问数量大,q发的情况下,毫无疑问是要选择q接池的,因ؓ(f)有连接池的功?无论是效率还是在资源利用率上都优?sh)DriverManagerDataSource <br /> <br />         从而从Ҏ(gu)上了(jin)解了(jin)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><bean id="pkmDataSource"   </li> <li>class="org.springframework.jndi.JndiObjectFactoryBean">  </li> <li>    <property name="jndiName" value="pkmDataSource"/>   </li> <li></bean>  </li> <li><!-- </li> <li>q样的话部v的时候,需要在容器中(tomcat,weblogicQ配|JDBC Connection Pool(DBCP)q接?nbsp;</li> <li>-->  </li> </ol> </div> <pre style="display: none;" name="code" class="xml"><bean id="pkmDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="pkmDataSource"/> </bean> <!-- q样的话部v的时候,需要在容器中(tomcat,weblogicQ配|JDBC Connection Pool(DBCP)q接? --> </pre> <br /> <br /> <strong>q三U连接方式常怋用,也容易؜淆,选择其中的某一U,需要看具体环境来配|了(jin)?/strong> <br /> <br /> <span style="font-size: medium;">PSQjdbc.properties文g中的配置如下</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  </li> <li>pkm.jdbc.url=jdbc":oracle":thin":@109.52.20.31":1521":orcl<!--把符号做转译-->  </li> <li>pkm.jdbc.name=pkmuser  </li> <li>pkm.jdbc.password=dbl0gin  </li> <li>pkm.jdbc.dataSource=pkmDataSource  </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)+'&u='+escape(d.location.href)+'&c='+escape(t),'saveit','scrollbars=no,width=590,height=300,left=75,top=20,status=no,resizable=yes'));saveit.focus();" class="fav_csdnstylebykimi" title="收藏到我的网摘(sh)Qƈ分nl我的朋?>收藏</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博客Q{载请标明出处Q? + 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提供?jin)两个这L(fng)数据源(都位于org.springframework.jdbc.datasourceE序包里Q:(x)<br /> DriverManagerDataSourceQ在每个q接h旉新徏一个连接。与DBCP的BasicDataSource不同QDriverManagerDataSource提供的连接没有进行池理?br /> SingleConnectionDataSourceQ在每个q接h旉q回同一个连接。虽然它不同严格意义上的池管理数据源Q但我们可以把它看作只有一个连接的池?br /> 对两个数据源的配|都cM于配|DBCP的BasicDataSource<br /> 区别在于׃DriverManagerDataSource和SingleConnectionDataSource都没有提供连接池Q所以在此没有设|池配置属性?br /> 虽然q两个数据源都对于小E序来说是很不错的,而且q在不断发展Q但把它们用于生产程序还是需要认真考虑的?/p> <p>SingleConnectionDataSource只用一个数据库q接Q所以不适合用于多线E程序。? DriverMangerDataSource虽然能够支持多线E,但它?x)在每次q接h旉新徏一个连接,q是以性能ZL(fng)。由于这些限Ӟ我们强烈 应该使用数据源池?/p> <p>在通过数据源与数据库徏立连接之后,我们p实际讉K数据库了(jin)Q而最基本的方式就是用JDBCQ现在我们就来看一看Spring如何让用简单的JDBC更加ѝ?br />  Spring在第三方依赖包中包含?jin)两个数据源的实现类包,其一是Apache的DBCPQ其二是 C3P0。可以在Spring配置文g中利用这两者中M一个配|数据源?/p> <p>DBCP数据?<br />      DBCP cd位于 /lib/jakarta-commons/commons-dbcp.jarQDBCP是一个依?Jakarta commons- pool对象池机制的数据库连接池Q所以在c\径下q必d?lib/jakarta- commons/commons-pool.jar。下面是?用DBCP配置MySql数据源的配置片断Q?/p> <p>xml 代码<br /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"        <br />          destroy-method="close">        <br />      <property name="driverClassName" value="com.mysql.jdbc.Driver" />       <br />      <property name="url" value="jdbc:mysql://localhost:3309/sampledb" />       <br />      <property name="username" value="root" />       <br />      <property name="password" value="1234" />       <br /> bean>   </p> <p>BasicDataSource提供?jin)close()Ҏ(gu)关闭数据源,所以必设定destroy-method=”close”属性, 以便Spring容器关闭Ӟ数据源能够正常关闭。除以上必须的数据源属性外Q还有一些常用的属性:(x) <br />      defaultAutoCommitQ设|从数据源中q回的连接是否采用自动提交机Ӟ默认gؓ(f) trueQ?<br />      defaultReadOnlyQ设|数据源是否仅能执行只读操作Q?默认gؓ(f) falseQ?<br />      maxActiveQ最大连接数据库q接敎ͼ讄?Ӟ表示没有限制Q?<br />      maxIdleQ最大等待连接中的数量,讄?Ӟ表示没有限制Q?<br />      maxWaitQ最大等待秒敎ͼ单位为毫U, 过旉?x)报出错误信息?<br />      validationQueryQ用于验证连接是否成功的查询SQL语句QSQL语句必须臛_要返回一行数据, 如你可以单地讄为:(x)“select count(*) from user”Q?<br />      removeAbandonedQ是否自我中断,默认?false Q?<br />      removeAbandonedTimeoutQ几U后数据q接?x)自动断开Q在removeAbandoned为trueQ提供该| <br />      logAbandonedQ是否记录中断事Ӟ 默认?falseQ?</p> <p>C3P0数据?<br />      C3P0 是一个开放源代码的JDBC数据源实现项目,它在lib目录中与Hibernate一起发布,实现?jin)JDBC3和JDBC2扩展规范说明? Connection 和Statement 池。C3P0cd位于/lib/c3p0/c3p0-0.9.0.4.jar。下面是使用C3P0配置一 ?oracle数据源:(x)</p> <p>xml 代码<br /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"        <br />          destroy-method="close">       <br />      <property name="driverClass" value=" oracle.jdbc.driver.OracleDriver "/>       <br />      <property name="jdbcUrl" value=" jdbc:oracle:thin:@localhost:1521:ora9i "/>       <br />      <property name="user" value="admin"/>       <br />      <property name="password" value="1234"/>       <br /> bean>   </p> <p>ComboPooledDataSource和BasicDataSource一h供了(jin)一个用于关闭数据源的close()Ҏ(gu)Q这h们就可以保证Spring容器关闭时数据源能够成功释放?<br />      C3P0拥有比DBCP更丰富的配置属性,通过q些属性,可以Ҏ(gu)据源q行各种有效的控Ӟ(x) <br />      acquireIncrementQ当q接池中的连接用完时QC3P0一ơ性创建新q接的数目; <br />      acquireRetryAttemptsQ定义在从数据库获取新连接失败后重复试获取的次敎ͼ默认?0Q?<br />      acquireRetryDelayQ两ơ连接中间隔旉Q单位毫U,默认?000Q?<br />      autoCommitOnCloseQ连接关闭时默认所有未提交的操作回滚。默认ؓ(f)falseQ?<br />      automaticTestTableQ? C3P0徏一张名为Test的空表,q用其自带的查询语句进行测试。如果定义了(jin)q个参数Q那么属性preferredTestQuery被忽略? ?不能在这张Test表上q行M操作Q它?yu)中为C3P0试所用,默认为nullQ?<br />      breakAfterAcquireFailureQ?获取q接p|会(x)引v所有等待获取连接的U程抛出异常。但是数据源仍有效保留,q在下次?nbsp;   用getConnection()的时候l尝试获取连 接。如果设为trueQ那么在试获取q接p|后该数据源将x(chng)已断开q永久关闭。默认ؓ(f) falseQ?<br />      checkoutTimeoutQ当q接池用完时客户端调用getConnection()后等待获取新q接的时_(d)时后将抛出SQLExceptionQ如设ؓ(f)0则无限期{待。单位毫U,默认?Q?<br />      connectionTesterClassNameQ? 通过实现ConnectionTester或QueryConnectionTester的类来测试连接,cd需讄为全限定名。默认ؓ(f) com.mchange.v2.C3P0.impl.DefaultConnectionTesterQ?<br />      idleConnectionTestPeriodQ隔多少U检查所有连接池中的I闲q接Q默认ؓ(f)0表示不检查; <br />      initialPoolSizeQ初始化时创建的q接敎ͼ应在minPoolSize与maxPoolSize之间取倹{默认ؓ(f)3Q?<br />      maxIdleTimeQ最大空闲时_(d)过I闲旉的连接将被丢弃。ؓ(f)0或负数则怸丢弃。默认ؓ(f)0Q?<br />      maxPoolSizeQ连接池中保留的最大连接数。默认ؓ(f)15Q?<br />      maxStatementsQ? JDBC的标准参敎ͼ用以控制数据源内加蝲的PreparedStatement数量。但׃预缓存的Statement? 于单个Connection 而不是整个连接池。所以设|这个参数需要考虑到多斚w的因素,如果maxStatements? maxStatementsPerConnection 均ؓ(f)0Q则~存被关闭。默认ؓ(f)0Q?<br />      maxStatementsPerConnectionQ连接池内单个连接所拥有的最大缓存Statement数。默认ؓ(f)0Q?<br />      numHelperThreadsQC3P0是异步操作的Q缓慢的JDBC操作通过帮助q程完成。扩展这些操作可以有效的提升性能Q通过多线E实现多个操作同时被执行。默认ؓ(f)3Q?<br />      preferredTestQueryQ定义所有连接测试都执行的测试语句。在使用q接试的情况下q个参数能显著提高测试速度。测试的表必d初始数据源的时候就存在。默认ؓ(f)nullQ?<br />      propertyCycleQ?用户修改pȝ配置参数执行前最多等待的U数。默认ؓ(f)300Q?<br />      testConnectionOnCheckoutQ? 因性能消耗大请只在需要的时候用它。如果设为true那么在每个connection提交的时候都 校验其有效性。徏议? idleConnectionTestPeriod或automaticTestTable <br /> {方法来提升q接试的性能。默认ؓ(f)falseQ?<br />      testConnectionOnCheckinQ如果设为true那么在取得连接的同时校验连接的有效性。默认ؓ(f)false?</p> <p>读配|文件的方式引用属性:(x) </p> <p><bean id="propertyConfigurer"      <br />          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">       <br />      <property name="location" value="/WEB-INF/jdbc.properties"/>       <br /> bean>       <br /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"        <br />          destroy-method="close">       <br />      <property name="driverClassName" value="${jdbc.driverClassName}" />       <br />      <property name="url" value="${jdbc.url}" />       <br />      <property name="username" value="${jdbc.username}" />       <br />      <property name="password" value="${jdbc.password}" />       <br /> bean>    </p> <p>     在jdbc.properties属性文件中定义属性|(x) <br />      jdbc.driverClassName= com.mysql.jdbc.Driver <br />      jdbc.url= jdbc:mysql://localhost:3309/sampledb <br />      jdbc.username=root <br />      jdbc.password=1234 <br />      提示 l常有开发者在${xxx}的前后不心(j)键入一些空|q些I格字符和变量合ƈ后作为属性的倹{如Q?的属性配|项Q在前后都有I格Q被解析后,username的gؓ(f)“ 1234 ”Q这造成最l的错误Q因此需要特别小?j)?/p> <p>获取JNDI数据?<br />      如果应用配置在高性能的应用服务器Q如WebLogic或Websphere{)(j)上,我们可能更希望用应用服务器本n提供的数据源。应用服务器的数据源 使用JNDI开放调用者用,Spring为此专门提供引用JNDI资源的JndiObjectFactoryBeancR下面是一个简单的配置Q?/p> <p>xml 代码<br /> <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">       <br />      <property name="jndiName" value="java:comp/env/jdbc/bbt"/>       <br /> bean>   </p> <p>通过jndiName指定引用的JNDI数据源名U?<br />      Spring 2.0取J2EE资源提供?jin)一个jee命名I间Q通过jee命名I间Q可以有效地化J2EE资源的引用。下面是使用jee命名I间引用JNDI数据源的配置Q?</p> <p>xml 代码<br /> <beans xmlns=http://www.springframework.org/schema/beans     <br /> xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance     <br /> xmlns:jee=http://www.springframework.org/schema/jee     <br /> xsi:schemaLocation="<a >http://www.springframework.org/schema/beans</a>      <br /> <a >http://www.springframework.org/schema/beans/spring-beans-2.0.xsd</a>      <br /> <a >http://www.springframework.org/schema/jee</a>     <br /> <a >       <br /> <jee:jndi-lookup id="dataSource" jndi-name=" java:comp/env/jdbc/bbt"/>       <br /> beans>   </p> <p>Spring的数据源实现c?<br />      Spring 本n也提供了(jin)一个简单的数据源实现类DriverManagerDataSource Q它位于 org.springframework.jdbc.datasource包中。这个类实现?jin)javax.sql.DataSource接口Q但 它ƈ? 有提供池化连接的机制Q每ơ调用getConnection()获取新连接时Q只是简单地创徏一个新的连接。因此,q个数据源类比较适合在单元测? 或简 单的独立应用中用,因ؓ(f)它不需要额外的依赖cR?<br />       下面Q我们来看一下DriverManagerDataSource的简单用:(x)当然Q我们也可以通过配置的方式直接用DriverManagerDataSource?/p> <p>java 代码<br /> DriverManagerDataSource ds = new DriverManagerDataSource ();       <br /> ds.setDriverClassName("com.mysql.jdbc.Driver");       <br /> ds.setUrl("jdbc:mysql://localhost:3309/sampledb");       <br /> ds.setUsername("root");       <br /> ds.setPassword("1234");       <br /> Connection actualCon = ds.getConnection();   </p> <p>结 </p> <p>     不管采用何种持久化技术,都需要定义数据源。Spring附带?jin)两个数据源的实现类包,你可以自行选择q行定义。在实际部vӞ我们可能?x)直接采用应用? 务器本n提供的数据源Q这Ӟ则可以通过JndiObjectFactoryBean或jee命名I间引用JNDI中的数据源?</p> <p>DBCP与C3PO配置的区别:(x)</p> <p>C3PO Q?/p> <p>xml 代码</p> <p><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">   <br />      <property name="driverClass">   <br />          <value>oracle.jdbc.driver.OracleDrivervalue>   <br />      property>   <br />      <property name="jdbcUrl">              <br />          <value>jdbc:oracle:thin:@10.10.10.6:1521:DataBaseNamevalue>   <br />       property>   <br />      <property name="user">   <br />          <value>testAdminvalue>   <br />      property>   <br />      <property name="password">   <br />          <value>123456value>   <br />      property>   <br /> bean>   </p> <p>DBCPQ?/p> <p>xml 代码<br /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">   <br />      <property name="driverClassName">   <br />          <value>oracle.jdbc.driver.OracleDrivervalue>   <br />      property>   <br />      <property name="url">              <br />          <value>jdbc:oracle:thin:@10.10.10.6:1521:DataBaseNamevalue>   <br />       property>   <br />      <property name="username">   <br />          <value>testAdminvalue>   <br />      property>   <br />      <property name="password">   <br />          <value>123456value>   <br />      property>   <br /> bean></p> </div> <br /> </div> <img src ="http://www.aygfsteel.com/sealyu/aggbug/311728.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2010-02-02 22:04 <a href="http://www.aygfsteel.com/sealyu/archive/2010/02/02/311728.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>SQL ?with as 用法(?http://www.aygfsteel.com/sealyu/archive/2009/11/12/302068.htmlsealsealThu, 12 Nov 2009 03:12:00 GMThttp://www.aygfsteel.com/sealyu/archive/2009/11/12/302068.htmlhttp://www.aygfsteel.com/sealyu/comments/302068.htmlhttp://www.aygfsteel.com/sealyu/archive/2009/11/12/302068.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/302068.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/302068.htmlwith
sql1 as (select to_char(a) s_name from test_tempa),
R ]F5^5"KFW0n B0sql2 as (select to_char(b) s_name from test_tempb where not exists (select s_name from sql1 where rownum=1))
select * from sql1ITPUB个hI间2g N*` O3y2eB Q6}
union all
select * from sql2
union all
select 'no records' from dual
       where not exists (select s_name from sql1 where rownum=1)
       and not exists (select s_name from sql2 where rownum=1);

再D个简单的例子

with a as (select * from test)

select * from a;

其实是把一大堆重复用到的SQL语句攑֜with as 里面Q取一个别名,后面的查询就可以用它

q样对于大批量的SQL语句起到一个优化的作用Q而且清楚明了(jin)


q是搜烦(ch)到的英文文档资料(说得比较?但是本h英文特菜,q没具体?jin)解?希望各高手具体谈谈这个with
as 的好?

About Oracle WITH clause
Starting in Oracle9i release 2 we see an incorporation of the SQL-99 “WITH clause”, a tool for materializing subqueries to save Oracle from having to re-compute them multiple times.

The SQL “WITH clause” 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 “WITH clause”:

   • The SQL “WITH clause” only works on Oracle 9i release 2 and beyond.
   • Formally, the “WITH clause” is called subquery factoring
   • The SQL “WITH clause” is used when a subquery is executed multiple times
   • Also useful for recursive queries (SQL-99, but not Oracle SQL)

To keep it simple, the following example only references the aggregations once, where the SQL “WITH clause” is normally used when an aggregation is referenced multiple times in a query.
We can also use the SQL-99 “WITH clause” instead of temporary tables. The Oracle SQL “WITH clause” will compute the aggregation once, give it a name, and allow us to reference it (maybe multiple times), later in the query.

The SQL-99 “WITH clause” is very confusing at first because the SQL statement does not begin with the word SELECT. Instead, we use the “WITH clause” to start our SQL query, defining the aggregations, which can then be named in the main query as if they were “real” tables:

WITH
subquery_name
AS
(the aggregation SQL statement)
SELECT
(query naming subquery_name);


Retuning to our oversimplified example, let’s replace the temporary tables with the SQL “WITH  clause”:

WITH
sum_sales AS
  select /*+ materialize */
    sum(quantity) all_sales from stores
number_stores AS
  select /*+ materialize */
    count(*) nbr_stores from stores
sales_by_store AS
  select /*+ materialize */
  store_name, sum(quantity) store_sales from
  store natural join sales
SELECT
   store_name
FROM
   store,
   sum_sales,
   number_stores,
   sales_by_store
where
   store_sales > (all_sales / nbr_stores)
;


Note the use of the Oracle undocumented “materialize” hint in the “WITH clause”. The Oracle materialize hint is used to ensure that the Oracle cost-based optimizer materializes the temporary tables that are created inside the “WITH” clause. This is not necessary in Oracle10g, but it helps ensure that the tables are only created one time.

It should be noted that the “WITH clause” does not yet fully-functional within Oracle SQL and it does not yet support the use of “WITH clause” replacement for “CONNECT BY” when performing recursive queries.

To see how the “WITH clause” is used in ANSI SQL-99 syntax, here is an excerpt from Jonathan Gennick’s great work “Understanding the WITH Clause” showing the use of the SQL-99 “WITH clause” to traverse a recursive bill-of-materials hierarchy

The SQL-99 “WITH clause” is very confusing at first because the SQL statement does not begin with the word SELECT. Instead, we use the “WITH clause” to start our SQL query, defining the aggregations, which can then be named in the main query as if they were “real” tables:

WITH
subquery_name
AS
(the aggregation SQL statement)
SELECT
(query naming subquery_name);


Retuning to our oversimplified example, let’s replace the temporary tables with the SQL “WITH” clause”:

另一个例?
with tempDeptName(deptName) as
(
      select
             dept_name as deptName
     from
             bas_dept as dept,tpp_materialmuster as muster
     where
             dept.DEPT_ID = muster.NEEDUNIT
           
     union all
     
     select
             corp_name as deptName
     from
              bas_corp as corp,tpp_materialmuster as muster
     where
             corp.corp_id = muster.NEEDUNIT
           
),
tempProjInfo(projName, projCode) as
(
      select
             etfprojName as projName,
            etfprojCode as projCode
     from
             tbi_etfproj as etf, tpp_materialMuster as muster
     where
             etf.etfprojid = muster.projid
           
     union all
     
     select
             etmprojName as projName,
            etmprojCode as projCode
     from
              tbi_etmproj as etm, tpp_materialMuster as muster
     where
               etm.etmprojId = muster.projid
)

select
                   deptname,
                   projname,
                   projcode
      from     tpp_materialmuster as muster,tempDeptName,tempProjInfo


seal 2009-11-12 11:12 发表评论
]]>
How to convert from string to datetime in sql server?http://www.aygfsteel.com/sealyu/archive/2009/11/05/301216.htmlsealsealThu, 05 Nov 2009 01:59:00 GMThttp://www.aygfsteel.com/sealyu/archive/2009/11/05/301216.htmlhttp://www.aygfsteel.com/sealyu/comments/301216.htmlhttp://www.aygfsteel.com/sealyu/archive/2009/11/05/301216.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/301216.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/301216.html阅读全文

seal 2009-11-05 09:59 发表评论
]]>
标注枚Dcd@EnumeratedQ{Q?/title><link>http://www.aygfsteel.com/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.aygfsteel.com/sealyu/archive/2009/06/30/284749.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/284749.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2009/06/30/284749.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/284749.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/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: ?hu)?">实体</span><font face="Times New Roman">Entity</font><span style="font-family: ?hu)?">中通过</span><font face="Times New Roman">@Enumerated</font><span style="font-family: ?hu)?">标注枚DcdQ例如将</span><font face="Times New Roman">CustomerEO</font><span style="font-family: ?hu)?">实体中增加一?/span><font face="Times New Roman">CustomerType</font><span style="font-family: ?hu)?">cd的枚丑֞属性,标注实体后的代码如下所C?/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;">……</font></span></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         private CustomerType type;</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </font></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         @Enumerated(EnumType.STRING)</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public CustomerType getType() {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">                   return type;</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         }</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public void setType(CustomerType type) {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">                   this.type = type;</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         }</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </font></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         public enum CustomerType {</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">                   COMPETITOR, INVESTOR, PARTNER, VENDER</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         }</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </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: ?hu)?">在实体中虽然标注成枚丄型,但当实体持久化后Q表中所对应的g旧是基本的数据类型,以上代码创徏表的</span><font face="Times New Roman">SQL</font><span style="font-family: ?hu)?">语句是:(x)</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;">         id int(20) NOT NULL auto_increment,</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         name varchar(255),</font></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         type varchar(255),</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         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: ?hu)?"><font size="3">使用枚Dcd后,在创建实体时便可以直接引用枚丄型,例如以下代码所C?/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: ?hu)?">在?/span><font face="Times New Roman">@Enumerated</font><span style="font-family: ?hu)?">注释Ӟ需要注意以下几个问题:(x)</span></font></p> <p style="margin: 0cm 0cm 0pt 21pt;"><span style="font-family: Wingdings;"><font size="3">l</font><span style="font-family: "Times New Roman"; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">         </span></span><font size="3"><span style="font-family: ?hu)?">因ؓ(f)枚Dcd的有名称和g个属性,所以在持久化时可以选择持久化名U或是持久化倹{通过</span><font face="Times New Roman">EnumType</font><span style="font-family: ?hu)?">来定义,它有两个值如下所C?/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: ?hu)?">表示持久化的为枚丄型的|</span><font face="Times New Roman">STRING</font><span style="font-family: ?hu)?">表示持久化的为枚丄型的名称。默认ؓ(f)</span><font face="Times New Roman">ORDINAL</font><span style="font-family: ?hu)?">Q持久化倹{例如以上示例中标注的ؓ(f)</span><font face="Times New Roman">STRING</font><span style="font-family: ?hu)?">Q这h久化实体后,数据库中保存的是枚Dcd的名Uͼ如图</span><span style="font-family: ?hu)?">所C?/span></font></p> <p style="margin: 0cm 0cm 12pt;" align="center"><span style="font-family: ?hu)?"><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: ?hu)?">若此时改?/span><font face="Times New Roman">ORDINAL</font><span style="font-family: ?hu)?">Q代码如下:(x)</span></font></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         @Enumerated(EnumType.ORDINAL)</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public CustomerType getType() {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">                   return type;</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: ?hu)?">则同h久化的实体后Q数据库保存的结果如?/span><span style="font-family: ?hu)?">所C?/span></font></p> <p style="margin: 0cm 0cm 12pt;" align="center"><span style="font-family: ?hu)?"><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: "Times New Roman"; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">         </span></span><font size="3"><span style="font-family: ?hu)?">如何选择</span><font face="Times New Roman">STRING</font><span style="font-family: ?hu)?">?/span><font face="Times New Roman">ORDINAL</font><span style="font-family: ?hu)?">Q?/span></font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: ?hu)?">如果使用</span><font face="Times New Roman">STRING</font><span style="font-family: ?hu)?">保存Q虽然从数据库中查询数据旉常直观,能够清楚的看?gu)cd代表意义Q但q样也会(x)带来其他的问题。若此时枚Dcd的定义改变,例如上例中的枚Dcd名称改ؓ(f)Q?/span></font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public enum CustomerType {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">                   CUST_COMPETITOR, INVESTOR, PARTNER, VENDER</font></strong></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: ?hu)?">则此时数据库中保存的“</span><font face="Times New Roman">COMPETITOR</font><span style="font-family: ?hu)?">”的值将不能转化为枚丄?/span><font face="Times New Roman">CustomerType</font><span style="font-family: ?hu)?">中的“</span><font face="Times New Roman">CUST_COMPETITOR</font><span style="font-family: ?hu)?">”的倹{但若?/span><font face="Times New Roman">ORDINAL</font><span style="font-family: ?hu)?">则不?x)带来这U问题。所以徏议?/span><font face="Times New Roman">ORDINAL</font><span style="font-family: ?hu)?">cd来持久化枚Dcd?/span></font></p> <p style="margin: 0cm 0cm 0pt 21pt;"><span style="font-family: Wingdings;"><font size="3">l</font><span style="font-family: "Times New Roman"; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">         </span></span><font size="3"><span style="font-family: ?hu)?">枚Dcd的定义位|,实体外部</span><font face="Times New Roman">VS</font><span style="font-family: ?hu)?">实体内部?/span></font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: ?hu)?">上例?/span><font face="Times New Roman">CustomerType</font><span style="font-family: ?hu)?">枚Dcd定义?/span><font face="Times New Roman">CustomerEO</font><span style="font-family: ?hu)?">实体内部Q这是因为只?/span><font face="Times New Roman">CustomerEO</font><span style="font-family: ?hu)?">q个实体?x)?/span><font face="Times New Roman">CustomerType</font><span style="font-family: ?hu)?">cdQ其他的实体不会(x)使用该类型。该cd与这个实体关pȝ密联pR?/span></font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: ?hu)?">但若此时多个实体公用一个枚丄型时Q则可以枚丄型单独定义,定义在实体的外部。有q样一个枚丄?/span><font face="Times New Roman">BusinessLine</font><span style="font-family: ?hu)?">Q它定义在实体外部,代码如下Q?/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;">         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: ?hu)?">例如</span><font face="Times New Roman">CustomerEO</font><span style="font-family: ?hu)?">实体增加一?/span><font face="Times New Roman">BusinessLine</font><span style="font-family: ?hu)?">的枚丄型,代码如下所C?/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;">……</font></span></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         private BusinessLine businessLine;</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         @Enumerated(EnumType.STRING)</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public BusinessLine getBusinessLine() {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">                   return businessLine;</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         }</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public void setBusinessLine(BusinessLine businessLine) {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">                   this.businessLine = businessLine;</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         }</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">}</font></p> <img src ="http://www.aygfsteel.com/sealyu/aggbug/284749.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2009-06-30 13:18 <a href="http://www.aygfsteel.com/sealyu/archive/2009/06/30/284749.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title> JAVAq接??http://www.aygfsteel.com/sealyu/archive/2009/03/13/259574.htmlsealsealFri, 13 Mar 2009 08:58:00 GMThttp://www.aygfsteel.com/sealyu/archive/2009/03/13/259574.htmlhttp://www.aygfsteel.com/sealyu/comments/259574.htmlhttp://www.aygfsteel.com/sealyu/archive/2009/03/13/259574.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/259574.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/259574.htmlpackage com.xinnuo.jdbc;

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;

 /*
  * 该类只能创徏一个实例,其它对象能够调用光(rn)态方法(也称为类Ҏ(gu)Q获得该唯一实例的引用?br />   * DBConnectionManagercȝ建构函数是私有的Q这是ؓ(f)?jin)避免其它对象创cȝ实例.
  * DBConnectionManagercȝ客户E序可以调用getInstance()Ҏ(gu)获得对该cd一实例的引用?br />   * cȝ唯一实例在getInstance()Ҏ(gu)W一ơ被调用期间创徏Q此后其引用׃直保存在?rn)态变?br />   * instance中。每ơ调用getInstance()都增加一个DBConnectionManager的客L(fng)序计数?br />   * 卻I该计C表引用DBConnectionManager唯一实例的客L(fng)序LQ它?yu)被用于控制q接池的
  * 关闭操作?该类实例的初始化工作U有Ҏ(gu)init()完成。其?getResourceAsStream()Ҏ(gu)
  * 用于定位q打开外部文g。外部文件的定位Ҏ(gu)依赖于类装蝲器的实现。标准的本地c装载器查找?br />   * 作L开始于cL件所在\径,也能够搜索CLASSPATH中声明的路径。db.properties是一个属?br />   * 文gQ它包含定义q接池的?值对。可供定义的公用属性如下:(x)
  *   drivers 以空格分隔的JDBC驱动E序cd?"
  *   logfile 日志文g的绝对\?
  *  其它的属性和特定q接池相养I其属性名字前应加上连接池名字Q?
  *  < poolname>.url 数据库的 JDBC URL
  *  < poolname>.maxconn 允许建立的最大连接数Q?表示没有限制
  *  < poolname>.user 用于该连接池的数据库帐号
  *  < poolname>.password 相应的密?"
  * 其中url属性是必需的,而其它属性则是可选的。数据库帐号和密码必d法。用于Windowsq_?br />   * db.properties文gCZ如下Q?br />   *  drivers=com.microsoft.jdbc.sqlserver.SQLServerDriver
  *  logfile=D:""log.txt
  *  access.maxconn=20
  *  access.url=jdbc:microsoft:sqlserver://localhost:1433;databasename=web
  *  access.user=sa
  *  access.password=sa 
  * 注意在Windows路径中的反斜杠必输?个,q是׃属性文件中的反斜杠同时也是一个{义字W?br />   * init()Ҏ(gu)在创建属性对象ƈddb.properties文g之后Q就开始检查logfile属性。如果属
  * 性文件中没有指定日志文gQ则默认为当前目录下的DBConnectionManager.log文g。如日志?br />   * 件无法用,则向System.err输出日志记录。装载和注册所有在drivers属性中指定的JDBC驱动
  * E序loadDrivers()Ҏ(gu)实现。该Ҏ(gu)先用StringTokenizerdrivers属性值分割ؓ(f)对应于驱
  * 动程序名U的字符Ԍ然后依次装蝲q些cdƈ创徏其实例,最后在DriverManager中注册该实例q把
  * 它加入到一个私有的向量drivers。向量drivers用于关闭服务时从DriverManager取消所?br />   * JDBC 驱动E序的注册。init()Ҏ(gu)的最后一个Q务是调用U有Ҏ(gu)createPools()创徏q接池对
  * 象。createPools()Ҏ(gu)先创建所有属性名字的枚D对象Q即Enumeration对象Q该对象可以惌
  * Z个元素系列,逐次调用其nextElement()Ҏ(gu)顺序返回各元素Q,然后在其中搜索名字以“.url”
  * l尾的属性。对于每一个符合条件的属性,先提取其q接池名字部分,q而读取所有属于该q接池的属性,
  * 最后创接池对象q把它保存在实例变量pools中。散列表QHashtablec?Qpools实现q接池名?br />   * 到连接池对象之间的映,此处以连接池名字为键Q连接池对象为倹{?Z于客L(fng)序从指定q接池获
  * 得可用连接或连接返回给q接池,cDBConnectionManager提供?jin)方法getConnection()?br />   * freeConnection()。所有这些方法都要求在参C指定q接池名字,具体的连接获取或q回操作则调
  * 用对应的q接池对象完成。ؓ(f)实现q接池的安全关闭QDBConnectionManager提供?jin)方法r(sh)elease()?br />   * 在上面我们已l提刎ͼ所有DBConnectionManager的客L(fng)序都应该调用?rn)态方法getInstance()
  * 以获得该理器的引用Q此调用增加客L(fng)序计数。客L(fng)序在关闭时调用release()可以递减该计数?br />   * 当最后一个客L(fng)序调用release()Q递减后的引用计数?Q就可以调用各个q接池的release()Ҏ(gu)
  * 关闭所有连接了(jin)。管理类release()Ҏ(gu)最后的d是撤销所有JDBC驱动E序的注册?br />   */

/**
 * 理cDBConnectionManager支持对一个或多个由属性文件定义的数据库连?br />  * 池的讉K.客户E序可以调用getInstance()Ҏ(gu)讉K本类的唯一实例.
 */
public class DBConnectionManager {
 static private DBConnectionManager instance; // 唯一实例

 static private int clients;

 private Vector drivers = new Vector();

 private PrintWriter log;

 private Hashtable pools = new Hashtable();

 /**
  * q回唯一实例.如果是第一ơ调用此Ҏ(gu),则创建实?br />   * @return DBConnectionManager 唯一实例
  */
 static synchronized public DBConnectionManager getInstance() {
  if (instance == null) {
   instance = new DBConnectionManager();
  }
  clients++;
  return instance;
 }

 /**
  * 建构函数U有以防止其它对象创建本cd?br />   */
 private DBConnectionManager() {
  init();
 }

 /**
  * * 连接对象返回给由名字指定的q接?br />   * @param name在属性文件中定义的连接池名字
  * @param conq接对象""""r
  */
 public void freeConnection(String name, Connection con) {
  DBConnectionPool pool = (DBConnectionPool) pools.get(name);
  if (pool != null) {
   pool.freeConnection(con);
  }
 }

 /**
  * 获得一个可用的(I闲?q接.如果没有可用q接,且已有连接数于最大连接数 053 * 限制,则创建ƈq回新连
  * @param name在属性文件中定义的连接池名字 056 *
  * @return Connection 可用q接或null 057
  */
 public Connection getConnection(String name) {
  DBConnectionPool pool = (DBConnectionPool) pools.get(name);
  if (pool != null) {
   return pool.getConnection();
  }
  return null;
 }

 /**
  * 获得一个可用连?若没有可用连?且已有连接数于最大连接数限制,
  * 则创建ƈq回新连?否则,在指定的旉内等待其它线E释放连?
  * @param name q接池名?071 *
  * @param time以毫U计的等待时?a>""""r
  * @return Connection 可用q接或null
  */
 public Connection getConnection(String name, long time) {
  DBConnectionPool pool = (DBConnectionPool) pools.get(name);
  if (pool != null) {
   return pool.getConnection(time);
  }
  return null;
 }

 /**
  * 关闭所有连?撤销驱动E序的注?a>""""r
  */
 public synchronized void release() {
  // {待直到最后一个客L(fng)序调?br />   if (--clients != 0) {
   return;
  }

  Enumeration allPools = pools.elements();
  while (allPools.hasMoreElements()) {
   DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
   pool.release();
  }
  Enumeration allDrivers = drivers.elements();
  while (allDrivers.hasMoreElements()) {
   Driver driver = (Driver) allDrivers.nextElement();
   try {
    DriverManager.deregisterDriver(driver);
    log("撤销JDBC驱动E序 " + driver.getClass().getName() + "的注?);
   } catch (SQLException e) {
    log(e, "无法撤销下列JDBC驱动E序的注? " + driver.getClass().getName());
   }
  }
 }

 /**
  * Ҏ(gu)指定属性创接池实例.
  * @param props q接池属?113
  */
 private void createPools(Properties props) {
  Enumeration propNames = props.propertyNames();
  while (propNames.hasMoreElements()) {
   String name = (String) propNames.nextElement();
   if (name.endsWith(".url")) {
    String poolName = name.substring(0, name.lastIndexOf("."));
    String url = props.getProperty(poolName + ".url");
    if (url == null) {
     log("没有接池" + poolName + "指定URL");
     continue;
    }
    String user = props.getProperty(poolName + ".user");
    String password = props.getProperty(poolName + ".password");
    String maxconn = props.getProperty(poolName + ".maxconn", "0");
    int max;
    try {
     max = Integer.valueOf(maxconn).intValue();
    } catch (NumberFormatException e) {
     log("错误的最大连接数限制: " + maxconn + " .q接? " + poolName);
     max = 0;
    }
    DBConnectionPool pool = new DBConnectionPool(poolName, url,
      user, password, max);
    pools.put(poolName, pool);
    log("成功创徏q接? + poolName);
   }
  }
 }

 /**
  * d属性完成初始化
  */
 private void init() {
  InputStream is = getClass().getResourceAsStream("/db.properties");
  Properties dbProps = new Properties();
  try {
   dbProps.load(is);
  } catch (Exception e) {
   System.err.println("不能d属性文? "+"L(fng)保db.properties在CLASSPATH指定的\径中");
   return;
  }
  String logFile = dbProps.getProperty("logfile","DBConnectionManager.log");
  try {
   log = new PrintWriter(new FileWriter(logFile, true), true);
  } catch (IOException e) {
   System.err.println("无法打开日志文g: " + logFile);
   log = new PrintWriter(System.err);
  }
  loadDrivers(dbProps);
  createPools(dbProps);
 }

 /**
  * 装蝲和注册所有JDBC驱动E序
  * @param props属?br />   */
 private void loadDrivers(Properties props) {
  String driverClasses = props.getProperty("drivers");
  StringTokenizer st = new StringTokenizer(driverClasses);
  while (st.hasMoreElements()) {
   String driverClassName = st.nextToken().trim();
   try {
    Driver driver = (Driver) Class.forName(driverClassName).newInstance();
    DriverManager.registerDriver(driver);
    drivers.addElement(driver);
    log("成功注册JDBC驱动E序" + driverClassName);
   } catch (Exception e) {
    e.printStackTrace();
    log("无法注册JDBC驱动E序: " + driverClassName + ", 错误: " + e);
   }
  }
 }

 /**
  * 文本信息写入日志文?br />   */
 private void log(String msg) {
  log.println(new Date() + ": " + msg);
 }

 /**
  * 文本信息与异常写入日志文g
  */
 private void log(Throwable e, String msg) {
  log.println(new Date() + ": " + msg);
  e.printStackTrace(log);
 }

 // ///////////////////////////////////////////////////////////////////////////////////////////////////////
 // ///////////////////////////////////////////////////////////////////////////////////////////////////////
 /*
  * DBConnectionPool实现Q它表示指向某个数据库的q接池。数据库由JDBC URL标识。一个JDBCURL׃部分l成Q协议标识(LjdbcQ,
  * 驱动E序标识Q如odbc、idb、oracle{)(j)Q数据库标识Q其格式依赖于驱动程序)(j)。例如,jdbc:odbc:demoQ即是一个指向demo数据
  * 库的JDBCURLQ而且讉K该数据库要用JDBC-ODBC驱动E序。每个连接池都有一个供客户E序使用的名字以?qing)可选的用户帐号、密码、最
  * 大连接数限制。如果Web应用E序所支持的某些数据库操作可以被所有用h行,而其它一些操作应q别许可的用户执行Q则可以ZcL?br />   * 分别定义q接池,两个q接池用相同的JDBC URLQ但使用不同的帐号和密码。类DBConnectionPool的徏构函数需要上q所有数据作为其
  * 参数。客L(fng)序可以用DBConnectionPool
  * cL供的两个Ҏ(gu)获取可用q接。两者的共同之处在于Q如q接池中存在可用q接Q则直接q回Q否则创建新的连接ƈq回。如果没有可用连?br />   * 且已有连接L{于最大限制数Q第一个方法将直接q回nullQ而第二个Ҏ(gu)等待直到有可用q接为止。所有的可用q接对象均登记在名ؓ(f)
  * freeConnections的向量(VectorQ中。如果向量中有多于一个的q接QgetConnection()L选取W一个。同Ӟ׃新的可用q接?br />   * 是从N加入向量Q从而得数据库q接׃长时间闲|而被关闭的风险减低到最程度?W一个getConnection()在返回可用连接给客户
  * E序之前Q调用了(jin)isClosed()Ҏ(gu)验证q接仍旧有效。如果该q接被关闭或触发异常QgetConnection()递归地调用自׃试获取另外?br />   * 可用q接。如果在向量freeConnections中不存在M可用q接QgetConnection()Ҏ(gu)(g)查是否已l指定最大连接数限制。如已经指定Q?br />   * 则检查当前连接数是否已经到达极限。此处maxConn?表示没有限制。如果没有指定最大连接数限制或当前连接数于该|该方法尝试创?br />   * 新的q接。如创徏成功Q则增加已用连接的计数q返回,否则q回I倹{创建新q接由newConnection()Ҏ(gu)实现?br />   * 创徏q程与是否已l指定数据库帐号、密码有兟뀂JDBC的DriverManagercL供多个getConnection()Ҏ(gu)Q这些方法要用到JDBC URL
  * 与其它一些参敎ͼ如用户帐号和密码{。DriverManager用指定的JDBC URL定适合于目标数据库的驱动程序及(qing)建立q接?br />   * W二个getConnection()Ҏ(gu)需要一个以毫秒为单位的旉参数Q该参数表示客户E序能够{待的最长时间。徏立连接的具体?br />   * 作仍旧由W一个getConnection()Ҏ(gu)实现。该Ҏ(gu)执行时先startTime初始化ؓ(f)当前旉。在while循环中尝试获得一个连接。如果失
  * 败,则以l定的时间gؓ(f)参数调用wait()。wait()的返回可能是׃其它U程调用notify()或notifyAll()Q也可能是由于预定时间已到?br />   * 为找出wait()q回的真正原因,E序用当前时间减开始时_(d)startTimeQ,如差值大于预定时间则q回I|否则再次调用getConnection()?br />   * 把空闲的q接登记到连接池由freeConnection()Ҏ(gu)实现Q它的参Cؓ(f)q回l连接池的连接对象。该对象被加入到freeConnections
  * 向量的末,然后减少已用连接计数。调用notifyAll()是ؓ(f)?jin)通知其它正在{待可用q接的线E?许多Servlet引擎为实现安全关闭提?br />   * 多种Ҏ(gu)。数据库q接池需要知道该事g以保证所有连接能够正常关闭。DBConnectionManagerc负协调整个关闭q程Q但关闭q接池中所有连
  * 接的d则由DBConnectionPoolc负责。release()Ҏ(gu)供DBConnectionManager调用。该Ҏ(gu)遍历freeConnections向量q关闭所有连接,
  * 然后从向量中删除q些q接?br />   */

 /**
  * 此内部类定义?jin)一个连接池.它能够根据要求创建新q接,直到预定的最""""r
  */
 class DBConnectionPool {
  private int checkedOut;

  private Vector freeConnections = new Vector();

  private int maxConn;

  private String name;

  private String password;

  private String URL;

  private String user;

  /**
   * 创徏新的q接?br />    * @param nameq接池名?br />    * @param URL数据库的JDBC URL
   * @param user数据库帐??null
   * @param password密码,?null
   * @param maxConn此连接池允许建立的最大连接数
   */
  public DBConnectionPool(String name, String URL, String user,
    String password, int maxConn) {
   this.name = name;
   this.URL = URL;
   this.user = user;
   this.password = password;
   this.maxConn = maxConn;
  }

  /**
   * 不再用的q接q回l连接池
   * @param con客户E序释放的连?br />    */
  public synchronized void freeConnection(Connection con) {
   // 指定连接加入到向量末尾
   freeConnections.addElement(con);
   checkedOut--;
   notifyAll();
  }

  /**
   * 从连接池获得一个可用连?如没有空闲的q接且当前连接数于最大连?数限?则创建新q接.
   * 如原来登Cؓ(f)可用的连接不再有?则从向量删除?
   * 然后递归调用自己以尝试新的可用连?
   */
  public synchronized Connection getConnection() {
   Connection con = null;
   if (freeConnections.size() > 0) {// 获取向量中第一个可用连?br />     con = (Connection) freeConnections.firstElement();
    freeConnections.removeElementAt(0);
    try {
     if (con.isClosed()) {
      log("从连接池" + name + "删除一个无效连?);
      // 递归调用自己,试再次获取可用q接
      con = getConnection();
     }
    } catch (SQLException e) {
     log("从连接池" + name + "删除一个无效连?);
     // 递归调用自己,试再次获取可用q接
     con = getConnection();
    }
   } else if (maxConn == 0 || checkedOut < maxConn) {
    con = newConnection();
   }
   if (con != null) {
    checkedOut++;
   }
   return con;
  }

  /**
   * 从连接池获取可用q接.可以指定客户E序能够{待的最长时?参见前一个getConnection()Ҏ(gu).
   * @param timeout以毫U计的等待时间限?br />    */
  public synchronized Connection getConnection(long timeout) {
   long startTime = new Date().getTime();
   Connection con;
   while ((con = getConnection()) == null) {
    try {
     wait(timeout);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    if ((new Date().getTime() - startTime) >= timeout) {// wait()q回的原因是时
     return null;
    }
   }
   return con;
  }

  /**
   * 关闭所有连?br />    */
  public synchronized void release() {
   Enumeration allConnections = freeConnections.elements();
   while (allConnections.hasMoreElements()) {
    Connection con = (Connection) allConnections.nextElement();
    try {
     con.close();
     log("关闭q接? + name + "中的一个连?);
    } catch (SQLException e) {
     log(e, "无法关闭q接? + name + "中的q接");
     e.printStackTrace();
    }
   }
   freeConnections.removeAllElements();
  }

  /**
   * 创徏新的q接
   */
  private Connection newConnection() {
   Connection con = null;
   try {
    if (user==null||"".equals(user)) {
     con = DriverManager.getConnection(URL);
    } else {
     con = DriverManager.getConnection(URL, user, password);
    }
    log("q接? + name + "创徏一个新的连?);
   } catch (SQLException e) {
    log(e, "无法创徏下列URL的连? " + URL);
    return null;
   }
   return con;
  }
 }

 /////////////////////////////////////////////////////////////////////////////////////////////
 /////////////////////////////////////////////////////////////////////////////////////////////
}

在sqlserver2000Qtomcat5.5验证通过

Ҏ(gu)调用Q?/p>

package com.xinnuo.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConn {
 private DBConnectionManager connMgr = null;
 private Connection conn = null;
 private Statement stat = null;
 private ResultSet rs = null;
 public DBConn() {
  connMgr = DBConnectionManager.getInstance();
 }
 public ResultSet executeQuery(String strSQL) throws SQLException {
  this.conn = connMgr.getConnection("access");
  this.stat = this.conn.createStatement();
  this.rs = this.stat.executeQuery(strSQL);
  return this.rs;
 }
 public void execute(String strSQL) throws SQLException {
  this.conn = connMgr.getConnection("access");
  this.stat = this.conn.createStatement();
  this.stat.execute(strSQL);
 }
 public void executeUpdate(String strSQL) throws SQLException {
  this.conn = connMgr.getConnection("access");
  this.stat = this.conn.createStatement();
  this.stat.executeUpdate(strSQL);
 }
 public Connection getConnection(){
  this.conn = connMgr.getConnection("access");
  return this.conn;
 }
 public void free(){
  try {
   if (this.rs != null) {
    this.rs.close();
   }
   if (this.stat != null) {
    this.stat.close();
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
  connMgr.freeConnection("access", this.conn);
 }
}

seal 2009-03-13 16:58 发表评论
]]>
SQL Server / MySQL 表名长度限制http://www.aygfsteel.com/sealyu/archive/2009/03/04/257793.htmlsealsealWed, 04 Mar 2009 07:12:00 GMThttp://www.aygfsteel.com/sealyu/archive/2009/03/04/257793.htmlhttp://www.aygfsteel.com/sealyu/comments/257793.htmlhttp://www.aygfsteel.com/sealyu/archive/2009/03/04/257793.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/257793.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/257793.html MySQL数据库名和表名长度限制ؓ(f)Q?4字符?br />


seal 2009-03-04 15:12 发表评论
]]>
Ubuntu下SQuirrelq接Microsoft SQL ServerQ很好的客户端)(j)http://www.aygfsteel.com/sealyu/archive/2009/01/14/251217.htmlsealsealWed, 14 Jan 2009 02:02:00 GMThttp://www.aygfsteel.com/sealyu/archive/2009/01/14/251217.htmlhttp://www.aygfsteel.com/sealyu/comments/251217.htmlhttp://www.aygfsteel.com/sealyu/archive/2009/01/14/251217.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/251217.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/251217.html Z把安装配|SQuirrel的过E中遇到到的问题记录一下,以免忘记Q?br /> 1。我安装的版本是SQuirrel2.6.8Q?在安装完成后启动Q显C出来的只有一个空H口Q除?jin)标题栏没Q何东西,Google?jin)一下,有h说是jdk版本的问题,׃目需要,必须使用jdk5Q看来只有安装两个jdk?jin)?可以q么作,原有jdk?qing)环境变量保持不变,再安装一个jdk6Q然后手动创Z个launcherQ启动参数设|ؓ(f)Q?usr/lib/jvm/java-6-sun/bin/java -jar /home/sealyu/tools/SQuirreL/squirrel-sql.jar ?br /> 2。不知道是否׃版本的原因,没找C用文档,SQuirrel官方|站也没扑ֈ。后来自己摸索了(jin)一下,惌q接到Microsoft SQL ServerQ这里我用的版本?005Q,下蝲?jin)最新的jtds驱动Q我的是jtds1.2.2.jar。将之放到SQuirrel_home/lib下面Q这样就能自动检到驱动Q打开SQuirrel后,在jTDS Microsoft SQL 右键Q选择Modify Driver, ?Extra Class Path 中选出你的jtds架包QList DriversQ这样你p在下面的下拉框中看到驱动的主cR点ȝ定按钮,q时候左Ҏ(gu)(wi)形菜单里面对应的条目前方qU色的小叉变?sh)绿色的对号了(jin)?br /> 3。新Z个AliasQ输入你要连接数据库的信息,connect卛_使用?br />



seal 2009-01-14 10:02 发表评论
]]>
SQL2005开发版安装中“性能监视器计数器要求Q错误)(j)”和“com+目录问题警告处理”问题的解决(?http://www.aygfsteel.com/sealyu/archive/2008/12/12/245888.htmlsealsealFri, 12 Dec 2008 03:29:00 GMThttp://www.aygfsteel.com/sealyu/archive/2008/12/12/245888.htmlhttp://www.aygfsteel.com/sealyu/comments/245888.htmlhttp://www.aygfsteel.com/sealyu/archive/2008/12/12/245888.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/245888.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/245888.html


?“开?#8221; -->  “q行”中输?regeditQ开启注册表~辑器?br />
定位?br /> [HKEY_LOCAL_MACHINE"SOFTWARE"Microsoft"Windows NT"CurrentVersion"Perflib
处,在右边的?wi)Ş目录下可以看到Perflib目录下有004?09两个子目录?br />
在Sql Server 2005 的安装帮助文件中说的是需要查?09目录的注册表,而我们大部分Z用的是简体中文的操作pȝQ所以不能按帮助中说的,而是需要注?04目录中的内容?br />
打开004 目录中的内容Q可以看到如下图Q?br />


我们分别双击 “Counter” ??“Help” ,察看其中的最后的数字Q如下图Q?br />
Counter 的内容Q?br />



Helper 内?br />


q时候,我们知道QCounter 的数字?556QHelper的内容?557?br />
然后Q操作注册表~辑器的左边的目录树(wi)Q定位到Perflib目录下,q注意检查右边窗口的 “Laster Counter”和“Laster Help”的|q把Laster Counter的值改成刚才记录下的Counter?556Q把Laster Help 的值改成刚才记下的 Help的?557?br />
要注意的是,修改数字的时候,输入的时候必选则基数?“十进?#8221;Q否则数字将不匹配,Sql Server 2005 (g)查将再次p|?br />
然后关闭注册表编辑器Q开始安?Sql Server 2005 Q绝对可以安装成功?

seal 2008-12-12 11:29 发表评论
]]>
RedHat AS4 下安装Bugzilla后不能连接MySQL问题的解x(chng)?/title><link>http://www.aygfsteel.com/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.aygfsteel.com/sealyu/archive/2008/07/20/216263.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/216263.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2008/07/20/216263.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/216263.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/sealyu/services/trackbacks/216263.html</trackback:ping><description><![CDATA[在RedHat AS4上安装BugzillaӞ<br /> 在安装完对应的perl模块后,在localconfig文g中配|mysql的对应信息,<br /> l箋(hu)q行checksetup.pl,出现如下错误Q?br /> Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)<br /> <br /> 但是Mysql已经安装q且能正常运行,后来发现Bugzilla 默认(g)查Mysql时是使用/var/lib/mysql/mysql.sockq行q接Q?br /> 而我使用源码~译安装的Mysql是?tmp/mysql.sock q行q接Q所以Bugzilla(g)查Mysql讄时会(x)出现q接错误?br /> 解决Ҏ(gu)很简单:(x)<br /> ln -s /tmp/mysql.sock /var/lib/mysql/mysql.sock<br /> q样每次Bugzillaq接时就?x)?tmp/mysql.sockq行q接Q安装成功?br /> <br /> <img src ="http://www.aygfsteel.com/sealyu/aggbug/216263.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2008-07-20 23:44 <a href="http://www.aygfsteel.com/sealyu/archive/2008/07/20/216263.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>在Redhat AS4上源码编译安装MySQLhttp://www.aygfsteel.com/sealyu/archive/2008/07/20/216256.htmlsealsealSun, 20 Jul 2008 14:32:00 GMThttp://www.aygfsteel.com/sealyu/archive/2008/07/20/216256.htmlhttp://www.aygfsteel.com/sealyu/comments/216256.htmlhttp://www.aygfsteel.com/sealyu/archive/2008/07/20/216256.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/216256.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/216256.htmlby Seal QHaibo YuQ?008-7-20


1>mysql安装文g(本h使用mysql5.0.51a-linux-i686-glibc23.tar.gz)解压到对应目录,在此?/home/seal/mysql

2>q入源码目录~译安装

CODE:

#cd /home/seal/mysql
#./configure --prefix=/usr/local/mysql --with-charset=gbk  |?配置Mysql安装路径q且支持中文
#make  |?~译
#make install  |?~译安装

3>替换/etc/my.cnf文g,q入源码?执行命o(h)

CODE:

#cd /home/seal/mysql
#cp support-files/my-medium.cnf /etc/my.cnf

4>建立MySQL使用者和组:

CODE:

#groupadd mysql
#useradd -g mysql mysql

5>完成以上操作以后q行初始化数据库,q入已经安装好的mysql目录

CODE:

#cd /usr/local/mysql
#bin/mysql_install_db --user=mysql  |?--user=mysql 初始化表q且规定用mysql用户
6>讄lmysql和root用户讑֮讉K权限 我们先进入mysql目录

CODE:

#cd /usr/local/mysql
#chown -R root /usr/local/mysql   |?讑֮root能访?usr/local/mysq
#chown -R mysql /usr/local/mysql/var   |?讑֮mysql用户能访?usr/local/mysql/var
#chgrp -R mysql /usr/local/mysql    |?讑֮mysqll能够访?usr/local/mysq
7>启动mysql,q入已经安装好的目录

CODE:

#cd /usr/local/mysql
#bin/mysqld_safe --user=mysql &

8>
修改mysql数据库超U用户root的缺省密?
/usr/local/mysql/bin/mysqladmin -u root password 'mysql'

关闭mysql服务?
cd /usr/local/mysql/bin
./mysqladmin -u root -p    shutdown 

9>讑֮开机就启动mysql,q入源码目录?/p>

# cd /home/seal/mysql
# cp support-files/mysql.server /etc/init.d/mysql

# chmod +x /etc/init.d/mysql
# chkconfig --level 345 mysql on
# service mysql restart
Shutting down MySQL.                                       [  定  ]
Starting MySQL                                                [  定  ]
[root@localhost mysql]#
10>讄Mysqlq程讉KQ?br /> 在启动mysql后:(x)
mysql>GRANT ALL PRIVILEGES ON *.* TO ‘myuser’@'%’ IDENTIFIED BY ‘mypassword’ WI
TH GRANT OPTION;
mysql>Flush Privileges;

安装完毕?br />


seal 2008-07-20 22:32 发表评论
]]>
mysql开启远E连接的Ҏ(gu)http://www.aygfsteel.com/sealyu/archive/2008/07/15/215088.htmlsealsealTue, 15 Jul 2008 14:36:00 GMThttp://www.aygfsteel.com/sealyu/archive/2008/07/15/215088.htmlhttp://www.aygfsteel.com/sealyu/comments/215088.htmlhttp://www.aygfsteel.com/sealyu/archive/2008/07/15/215088.html#Feedback3http://www.aygfsteel.com/sealyu/comments/commentRss/215088.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/215088.html解决MySQL不允总q程讉K的方?/span>

解决Ҏ(gu)Q?/span>
1
?/span>改表法。可能是你的帐号不允总q程登陆Q只能在localhost。这个时候只要在localhost的那台电(sh)脑,dmysql后,更改 “mysql” 数据库里?/span> “user” 表里?/span> “host” ,?/span>“localhost”改称“%”

mysql -u root -pvmwaremysql>use mysql;
mysql>update user set host = ‘%’ where user = ‘root’;
mysql>select host, user from user;

2. 授权法。例如,你想myuser使用mypassword从Q何主接到mysql服务器的话?/span>

GRANT ALL PRIVILEGES ON *.* TO ‘myuser’@'%’ IDENTIFIED BY ‘mypassword’ WI
TH GRANT OPTION;

如果你想允许用户myuser?/span>ip?/span>192.168.1.6的主接到mysql服务器,q?/span>mypassword作ؓ(f)密码

GRANT ALL PRIVILEGES ON *.* TO ‘myuser’@'192.168.1.3′ IDENTIFIED BY
‘mypassword’ WITH GRANT OPTION;

我用的第一个方?/span>,刚开始发C?/span>,在网上查?jin)一?/span>,执行一个语?/span> mysql>FLUSH   PRIVILEGES
使修改生?/span>.可以了(jin)

seal 2008-07-15 22:36 发表评论
]]>
SQL Server日期处理datetime和date之间的相互{?/title><link>http://www.aygfsteel.com/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.aygfsteel.com/sealyu/archive/2008/07/03/212308.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/212308.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2008/07/03/212308.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/212308.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/sealyu/services/trackbacks/212308.html</trackback:ping><description><![CDATA[<p><font size="1"><span>日期是数据处理中l常使用到的信息之一。生日、数据处理时间、计划的预计完成旉Q按q、季、月的统 计,q些都属于日期处理的范畴。由于日期中包含?jin)年、季、月、日{众多信息,不同的国家对日期格式、日期文字描q及(qing)星期有不同的规定Q因此生了(jin)日期处理 的复杂性。本章主要讨论在</span>SQL Server数据库中Ҏ(gu)期的各种处理Ҏ(gu)?/font></p> <h2 align="center"><font face="?hu)? MS Song" size="1">日期cd概述</font></h2> <p><font size="1">SQL Server中的日期cd包括datetime和smalldatetimeQ仅能处理可以识别ؓ(f)1753q_(d)9999q间的日期的|没有单独的日期型或时间型?/font></p> <h4><font face="?hu)? MS Song"><font size="1">1Qdatetime</font></font></h4> <p><font size="1">datetimecd处理?753q??日~9999q?2?1日的日期和时间数据,_度ؓ(f)癑ֈ之三U。即Q对?.000?.001?.009的日期|调整?.000Q对?.002?.004的日期|调整?.003Q对?.005?.008的日期|调整?.007?/font></p> <p><font size="1">例如Q下面的代码在输入时Q其旉_度ؓ(f)癑ֈ之一U,但经数据库保存后再显C出来,其结果就已经做了(jin)处理?/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>l果</font></p> <p><font size="1"><font face="Courier New">date                     </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    1900-01-01 00:00:00.000<br /> ...<br /> <font face="Courier New">1900-1-1 00:00:00.000    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的存储长度ؓ(f)8字节Q日期和旉各用4个字节存储,W一?字节存储?900q??日之前或之后的天敎ͼ?900q??日ؓ(f)分界点,?900q??日之前的日期的天数小?Q在1900q??日之后的日期的天数大?Q。另外一?字节存储以午夜(00:00:00.000Q后毫秒数所代表的每天的旉?/font></p> <p><font size="1">例如Q下面的代码演示?jin)datetime变量中,仅包含单U的日期和单U的旉Ӟ日期存储的十六进制存储表C结果?/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>l果<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>l果<font face="Courier New">: 0x000000000000012C</font></font></p> <h4><font face="?hu)? MS Song"><font size="1">2Qsmalldatetime</font></font></h4> <p><font size="1">smalldatetimecd处理?900q??日~2079q?? 日的日期和时间数据,_到分钟?9.998U或更低的smalldatetime值向下舍入ؓ(f)最接近的分钟,29.999U或更高的smalldatetime值向上舍入ؓ(f)最接近的分钟?/font></p> <p><font size="1">smalldatetime的存储长度ؓ(f)4字节Q第一?字节存储?900q??日之后的天数。另外一?字节存储午夜Q?0:00:00.000Q后的分钟数?/font></p> <p><font size="1">例如Q下面的代码演示?jin)smalldatetime变量中,仅包含单U的日期和单U的旉Ӟ日期存储的十六进制存储表C结果?/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>l果<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>l果<font face="Courier New">: 0x0000000A</font></font></p> <h2><font face="?hu)? MS Song" size="1">日期处理函数</font></h2> <p><font size="1">日期由年、月、日、时{多个部分组成,它的处理相对复杂Q因此,SQL Server提供?jin)大量的日期处理函数Q用以完成各U日期数据的处理。掌握好q些函数Q对完成数据库的各种日期处理非常必要Q本节将介绍几个常用的日期处理函数。期增减函数可以Ҏ(gu)期指定部分的D行增减,q返回处理后的日期|SQL Server提供的日期增减函Cؓ(f)DATEADD?/font></p> <p><br /> <font size="1">DATEADD</font><font size="1">的具体语法如下:(x)<font face="Courier New">DATEADD ( datepart , number, date )</font></font></p> <p><font size="1">其中包括以下参数?/font></p> <p><font size="1">¡ datepartQ是规定应向日期的哪一部分q回新值的参数。表2-1列出?jin)SQL Server支持的日期部分、羃写及(qing)含义?/font></p> <p><font size="1"><font face="?hu)? MS Song">                    DATEADD</font>?font face="?hu)? MS Song">DATEDIFF</font>支持的日期部分、羃写及(qing)含义</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="?hu)? MS Song">    </font>?/font></p> </td> <td valign="top" width="187"> <p><font size="1">?font face="?hu)? MS Song">    </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">q䆾</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">U?/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">¡ numberQ是用来增加datepart的倹{正数表C增加,负数表示减少Q如果指定的是非整数|则忽略此值的数部分Q不做四舍五入处理。例如,DATEADDQDay,1.7,dateQ,表示date增加1天?/font></p> <p><font size="1">¡ dateQ是q回datetime或smalldatetime值或日期格式字符串的表达式?/font></p> <p><font size="1">如果date是smalldatetimeQ则q回smalldatetimeQ否则返回datetime。date为smalldatetimeQDatepart为SecondQss,sQ或MillisecondQmsQ时Q返回值将Ҏ(gu)日期增减的结果调整到分钟Qdate为datetimeQDatepart为MillisecondQmsQ时Q返回值将Ҏ(gu)日期增减的结果调整ؓ(f)癑ֈ之三U。调整规则可以参?.1节的相关说明?/font></p> <p><font size="1">date允许直接与numberq行增减计算Q即对于DATEADDQDay,number,dateQ,{同于date+number?/font></p> <h3><font face="?hu)? MS Song"><font size="1"> 日期信息获取函数</font></font></h3> <p><font size="1">日期信息获取函数用于获取日期指定部分的相关信息,常用的日期信息获取函数如?-2所C?/font></p> <p><font size="1"><font face="?hu)? MS Song">                                      </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="?hu)? MS Song">    </font>?/font></p> </td> <td valign="top" width="253"> <p><font size="1">参数?qing)返回值数据类型说?/font></p> </td> </tr> <tr> <td valign="top" width="140"> <p><font size="1">q回代表指定日期的指定日期部分的字符?/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是指定应q回的日期部分的参数Q其定义如表2-3所C。date是返回datetime或smalldatetime值或日期格式字符串的表达式。DATENAME函数q回nvarcharQDATEPART函数q回int</font></p> </td> </tr> <tr> <td valign="top" width="140"> <p><font size="1">q回代表指定日期的指定日期部分的整数</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">q回表示指定日期中的q䆾的整?/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">q回int</font></p> </td> </tr> <tr> <td valign="top" width="140"> <p><font size="1">q回表示指定日期中的月䆾的整?/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">q回int</font></p> </td> </tr> <tr> <td valign="top" width="140"> <p><font size="1">q回表示指定日期中的天的整数</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">q回int</font></p> </td> </tr> </tbody> </table> <p><font size="1"><font face="?hu)? MS Song">                  DATENAME</font>?font face="?hu)? MS Song">DATEPART</font>支持的日期部分、羃写及(qing)含义</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="?hu)? MS Song">    </font>?/font></p> </td> <td valign="top" width="253"> <p><font size="1">?font face="?hu)? MS Song">    </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">q䆾</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">自年初开始的W几个星?/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">星期几(例如星期一、星期二Q?/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">U。date为smalldatetimeӞ始终q回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Ӟ始终q回0Qؓ(f)datetimeӞq回百䆾之三U?/font></p> </td> </tr> </tbody> </table> <p><font size="1">DATEPARTQWeek,dateQ返回的星期计算方式Q是按照星期日ؓ(f)一周的W一天,q点与中国h的日期处理习(fn)惯不同,在用时要注意这一炏VDATENAME函数q回指定日期的指定日期部分的字符Ԍ其返回的具体字符串|与SET DATEFIRST?qing)SET DATELANGUAGE选项的设|有兟뀂用DATEPARTQWeekday,dateQ时Q其q回的gSET DATEFIRST选项的设|有养I具体的将?.3节中说明?/font></p> <h3><font face="?hu)? MS Song"><font size="1"> 日期差D函?/font></font></h3> <p><font size="1">日期差D函数用于计两个给定日期指定部分的边界敎ͼSQL Server提供的日期差D函Cؓ(f)DATEDIFF?/font></p> <p><font size="1">DATEDIFF的具体语法如下:(x)</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">¡ datepartQ规定了(jin)应在日期的哪一部分计算差额Q其定义如表2-1所C?/font></p> <p><font size="1">¡ startdateQ规定了(jin)计算的开始日期?/font></p> <p><font size="1">¡ enddateQ规定了(jin)计算的终止日期?/font></p> <p><font size="1">q回cdQinteger</font></p> <p><font size="1">计算的开始日期和l止日期Q可以是日期或日期格式的字符丌Ӏ计的Ҏ(gu)是从enddate减去startdate。如果startdate比enddate晚,q回负倹{当l果出整数D_(d)DATEDIFF׃生错误。对于毫U,最大数?4?0时31分钟23.647U。对于秒Q最大数?8q?/font></p> <p><font size="1">计算跨分钟、秒和毫U这些边界的Ҏ(gu)Q得DATEDIFFl出的结果在全部数据cd中是一致的。结果是带正负号的整数|其等于跨W一个和W二个日期间的datepart边界数。例如,?005q??日和2005q??1日之间的月䆾数是1?/font></p> <h3><font face="?hu)? MS Song"><font size="1"> 其他日期处理相关函数</font></font></h3> <p><font size="1">其他常用的日期处理相兛_数包括以下几个?/font></p> <h4><font face="?hu)? MS Song"><font size="1">1QGETDATE</font></font></h4> <p><font size="1">GETDATE按照datetimeD回当前系l日期和旉?/font></p> <p><font size="1">GETDATE的语法如下:(x)</font></p> <p><font face="Courier New" size="1">GETDATE()</font></p> <p><font size="1">q回cdQdatetime</font></p> <h4><font face="?hu)? MS Song"><font size="1">2QISDATE</font></font></h4> <p><font size="1">ISDATE定输入的表辑ּ是否有效日期?/font></p> <p><font size="1">在输入日期表辑ּӞ日期都是以日期格式的字符串提供的Q由于不同的区域有不同的日期格式Q所以ƈ不能保证输入的日期表辑ּ能够被SQL Server识别Q这U情况下Q就需要用ISDATE来判断日期表辑ּ能否正确地被SQL Server识别?jin)?/font></p> <p><font size="1">ISDATE的语法如下:(x)</font></p> <p><font face="Courier New" size="1">ISDATE(expression)</font></p> <p><font size="1">q回cdQint</font></p> <h4><font face="?hu)? MS Song"><font size="1">3QCONVERT</font></font></h4> <p><font size="1">CONVERT某U数据类型的表达式显式{换ؓ(f)另一U数据类型?/font></p> <p><font size="1">严格来说QCONVERT不属于日期处理函敎ͼ只是它被l常用于日期处理中,所以这里把它列入了(jin)其他日期处理函数Q下面是CONVERT的用法描qͼ只重点说明在日期处理中的应用Q?/font></p> <p><font size="1">CONVERT的具体语法如下:(x)</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">¡ expressionQ是要{换数据类型的有效SQL Server表达式?/font></p> <p><font size="1">¡ data_typeQ是expression转换后的数据cdQlength是对于有_ֺ定义需要的data_type的精度定义,对于没有_ֺ定义需要的data_typeQ该参数可以省略?/font></p> <p><font size="1">¡ styleQ定义数据类型{换时的格式,对于日期cd的{换,它的定义如表2-4所C?/font></p> <p><font size="1">?font face="?hu)? MS Song">2-4                                      style</font>在日期{换中的说?/font></p> <table border="1" cellpadding="0" cellspacing="0" width="561"> <tbody> <tr> <td valign="top" width="105"> <p><font size="1">不带世纪C</font></p> </td> <td valign="top" width="84"> <p><font size="1">带世U数?/font></p> </td> <td valign="top" width="141"> <p><font size="1">?font face="?hu)? MS Song">    </font>?/font></p> </td> <td valign="top" width="230"> <p><font size="1">输入<font face="?hu)? 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?00</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?09</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?13</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?20</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?21</font></p> </td> <td valign="top" width="141"> <p><font size="1">ODBC规范Q带毫秒Q?/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="?hu)? MS Song">Q?/font></font></p> <p><font face="?hu)? MS Song" size="1">?nbsp;输入/输出Q?#8220;输入”表示从字W串转换为日期时字符串的日期格式Q?#8220;输出”指从日期转换为字W串时的日期字符串格式?/font></p> <p><font face="?hu)? MS Song" size="1">?nbsp;HijriQ是h几种变化形式的日历系l,SQL Server使用其中的科威特法?/font></p> </div> <p><font size="1">当从smalldatetime转换为字W数据时Q由于smalldatetimer只保存到分钟的数据,因此Q对于包含秒或毫U的样式Q将在秒或毫U的位置上显C零。当从datetime或smalldatetimeD行{换时Q可以通过使用适当的char或varchar数据cd长度来截断不需要的日期部分?/font></p> <div> <p><font size="1">注意<font face="?hu)? MS Song">Q?/font></font></p> <p><font face="?hu)? MS Song" size="1">在SQL Server中,׃直接提供的日期均是以日期格式的字W串提供Q所以在使用CONVERTq行日期格式转换Ӟ要先把日期格式的字符串{换ؓ(f)日期型,然后才能利用CONVERTq行日期格式转换Q否则就变成字符串{换ؓ(f)字符Ԍ此时的style选项是无效的?/font></p> </div> <p><font size="1">q回cdQ由参数data_type定?/font></p> <p><font size="1">下面是利用CONVERTq行日期转换的简单示例:(x)</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>表示日期字符串ؓ(f)<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>l果<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>表示日期字符串ؓ(f)<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>l果<font face="Courier New">:2003-01-11 00:00:00.000</font><font face="Courier New"> </font></font></p> <p><font size="1"><font face="Courier New">/*== </font>日期转换为字W串<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>表示日期{换ؓ(f)<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>l果<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>表示日期{换ؓ(f)<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>l果<font face="Courier New">:11/01/2003</font></font></p> <p><font size="1"><font face="Courier New"> </font><font face="Courier New">/*== </font>q是很多人经常犯的错?font face="Courier New">,</font>寚w日期型{换用日期的<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>l果</font><font face="Courier New" size="1">:2003-1-11</font> <img src ="http://www.aygfsteel.com/sealyu/aggbug/212308.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2008-07-03 13:38 <a href="http://www.aygfsteel.com/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:connecthttp://www.aygfsteel.com/sealyu/archive/2008/07/01/212000.htmlsealsealTue, 01 Jul 2008 13:07:00 GMThttp://www.aygfsteel.com/sealyu/archive/2008/07/01/212000.htmlhttp://www.aygfsteel.com/sealyu/comments/212000.htmlhttp://www.aygfsteel.com/sealyu/archive/2008/07/01/212000.html#Feedback4http://www.aygfsteel.com/sealyu/comments/commentRss/212000.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/212000.html Connection refused: connect
l过几小时的?zhun)扎Q在配置理器里面发C(jin)问题Q原来是TCPIP服务没有默认打开Q解军_下:(x)
1、打开SQL Server Configuration Manager -> Protocols for SQLEXPRESS -> TCP/IP
2、右键单d动TCP/IP
3、双击进入属性,把IP地址中的IP all中的TCP端口讄?433
4、重新启动SQL Server 2005服务




seal 2008-07-01 21:07 发表评论
]]>
sql server 中删除默认约束的通用sql脚本http://www.aygfsteel.com/sealyu/archive/2008/04/17/193755.htmlsealsealThu, 17 Apr 2008 06:31:00 GMThttp://www.aygfsteel.com/sealyu/archive/2008/04/17/193755.htmlhttp://www.aygfsteel.com/sealyu/comments/193755.htmlhttp://www.aygfsteel.com/sealyu/archive/2008/04/17/193755.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/193755.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/193755.html 在SQL Server 中,如果l表的一个字D设|了(jin)默认|׃(x)在系l表sysobjects中生成一个默认约束?br /> 如果惛_除这个设|了(jin)默认值的字段Q假设此字段名column1Q,
执行“ALTER TABLE table1 DROP COLUMN column1”时就?x)报错?x)
The object 'DF__xxxxxxxxxxx' is dependent on column 'column1'.
ALTER TABLE DROP COLUMN column1failed because one or more objects access this column.

所以在删除此字D|需要先系l表中的对应默认U束删除Q?可以使用下面的脚本进行删除:(x)
-- this script drops the default constraint which is generated by the setting of default value.
DECLARE @tablename VARCHAR(100), @columnname VARCHAR(100), @tab VARCHAR(100)
SET @tablename='CountryGroupEmailAndWaitAux'
SET @columnname='actionOfHasNoValidEmail'

declare @defname varchar(100)
declare @cmd varchar(100)

select @defname = name
FROM sysobjects so
JOIN sysconstraints sc
ON so.id = sc.constid
WHERE object_name(so.parent_obj) = @tablename
AND so.xtype = 'D'
AND sc.colid =
(SELECT colid FROM syscolumns
WHERE id = object_id(@tablename) AND
name = @columnname)

select @cmd='alter table '+ @tablename+ ' drop constraint '+ @defname
if @cmd is null print 'No default constraint to drop'
exec (@cmd)

在删除对应的默认U束后,执行Q?br /> ALTER TABLE table1 DROP COLUMN column1
卛_删除字段?br />

seal 2008-04-17 14:31 发表评论
]]>
使用一条SQL语句删除表中重复记录Q{载)(j)http://www.aygfsteel.com/sealyu/archive/2008/04/10/192010.htmlsealsealThu, 10 Apr 2008 14:55:00 GMThttp://www.aygfsteel.com/sealyu/archive/2008/04/10/192010.htmlhttp://www.aygfsteel.com/sealyu/comments/192010.htmlhttp://www.aygfsteel.com/sealyu/archive/2008/04/10/192010.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/192010.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/192010.html

数据库结构的脚本:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TempA]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TempA]
GO

CREATE TABLE [dbo].[TempA] (
 [id] [int] IDENTITY (1, 1) NOT NULL ,
 [PositionName] [varchar] (256) COLLATE Chinese_PRC_CI_AS NULL ,
 [EnglishPositionName] [varchar] (256) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[TempA] ADD
 CONSTRAINT [PK_TempA] PRIMARY KEY  CLUSTERED
 (
  [id]
 )  ON [PRIMARY]
GO

TempA表中有三个字D?id唯一且ؓ(f)主键,自动增长; PositionName,EnglishPositionName中有重复的记?比如:
id      PositionName        EnglishPositionName
20     其他                           Others
21     质量工程?nbsp;              QC Engineer
22     其他                           Others
.......
100  质量工程?nbsp;              QC Engineer
需要剔除重复的"其他","质量工程?{记录?/p>

采用的SQL语句Q?br /> Delete from TempA where id not in (
        select max(t1.id) from TempA t1 group by
         t1.PositionName,t1.EnglishPositionName)

说明Q?br /> (1)需要剔除那几个用于判断重复的字D,则将它们攑֜group by语句之后?br /> (2)max(t1.id) 也可以改成:(x)min(t1.id)



seal 2008-04-10 22:55 发表评论
]]>
վ֩ģ壺 | | Ͷ| ̫| ݰ| ³ƶ| Ī| | ɽ| | Ӽ| | | | | г| | ͼ| ԭƽ| | | | ɽ| | | | | ϲ| | | | Դ| ̨| | | | н| | | Զ| |