2008年1月14日星期一

【SQL-ADO】SQL SERVER 连接字符串大全

baidu

 

转自:http://www.connectionstrings.com/

   SQL Server

  •  ODBC
    • Standard Security:

"Driver={SQL Server};Server=Aron1;Database=pubs;Uid=sa;Pwd=asdasd;"

    •  Trusted connection:

"Driver={SQL Server};Server=Aron1;Database=pubs;Trusted_Connection=yes;"

    •  Prompt for username and password:

oConn.Properties("Prompt") = adPromptAlways
oConn.Open "Driver={SQL Server};Server=Aron1;DataBase=pubs;"

  •  OLE DB, OleDbConnection (.NET)
    •  Standard Security:

"Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;User Id=sa;Password=asdasd;"

    •  Trusted Connection:

"Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;"

(use serverName\instanceName as Data Source to use an specifik SQLServer instance, only SQLServer2000)

    •  Prompt for username and password:

oConn.Provider = "sqloledb"
oConn.Properties("Prompt") = adPromptAlways
oConn.Open "Data Source=Aron1;Initial Catalog=pubs;"

    •  Connect via an IP address:

"Provider=sqloledb;Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;"

(DBMSSOCN=TCP/IP instead of Named Pipes, at the end of the Data Source is the port to use (1433 is the default))

  •  SqlConnection (.NET)
    • Standard Security:

"Data Source=Aron1;Initial Catalog=pubs;User Id=sa;Password=asdasd;"
   - or -
"Server=Aron1;Database=pubs;User ID=sa;Password=asdasd;Trusted_Connection=False"
   (both connection strings produces the same result)

    •  Trusted Connection:

"Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;"
   - or -
"Server=Aron1;Database=pubs;Trusted_Connection=True;"
   (both connection strings produces the same result)

(use serverName\instanceName as Data Source to use an specifik SQLServer instance, only SQLServer2000)

    •  Connect via an IP address:

"Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;"

(DBMSSOCN=TCP/IP instead of Named Pipes, at the end of the Data Source is the port to use (1433 is the default))

    •  Declare the SqlConnection:

C#:
using System.Data.SqlClient;
SqlConnection oSQLConn = new SqlConnection();
oSQLConn.ConnectionString="my connection string";
oSQLConn.Open();

 

VB.NET:
Imports System.Data.SqlClient
Dim oSQLConn As SqlConnection = New SqlConnection()
oSQLConn.ConnectionString="my connection string"
oSQLConn.Open()

  •  Data Shape




    •  MS Data Shape
      "Provider=MSDataShape;Data Provider=SQLOLEDB;Data Source=Aron1;Initial Catalog=pubs;User ID=sa;Password=asdasd;"

Want to learn data shaping? Check out 4GuyfFromRolla's great article about Data Shaping >>

  •  Read more




    •  How to define which network protocol to use
      • Example:
        "Provider=sqloledb;Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;"

Name

Network library

dbnmpntw

Win32 Named Pipes

dbmssocn

Win32 Winsock TCP/IP

dbmsspxn

Win32 SPX/IPX

dbmsvinn

Win32 Banyan Vines

dbmsrpcn

Win32 Multi-Protocol (Windows RPC)



      • Important note!
        When connecting through the SQLOLEDB provider use the syntax Network Library=dbmssocn
        and when connecting through MSDASQL provider use the syntax Network=dbmssocn
    •  All SqlConnection connection string properties
      • This table shows all connection string properties for the ADO.NET SqlConnection object. Most of the properties are also used in ADO. All properties and descriptions is from msdn.

Name

Default

Description

Application Name

 

The name of the application, or '.Net SqlClient Data Provider' if no application name is provided.

AttachDBFilename
-or-
extended properties
-or-
Initial File Name

 

The name of the primary file, including the full path name, of an attachable database. The database name must be specified with the keyword 'database'.

Connect Timeout
-or-
Connection Timeout

15

The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.

Connection Lifetime

0

When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by connection lifetime. Useful in clustered configurations to force load balancing between a running server and a server just brought on-line.

Connection Reset

'true'

Determines whether the database connection is reset when being removed from the pool. Setting to 'false' avoids making an additional server round-trip when obtaining a connection, but the programmer must be aware that the connection state is not being reset.

Current Language

 

The SQL Server Language record name.

Data Source
-or-
Server
-or-
Address
-or-
Addr
-or-
Network Address

 

The name or network address of the instance of SQL Server to which to connect.

Enlist

'true'

When true, the pooler automatically enlists the connection in the creation thread's current transaction context.

Initial Catalog
-or-
Database

 

The name of the database.

Integrated Security
-or-
Trusted_Connection

'false'

Whether the connection is to be a secure connection or not. Recognized values are 'true', 'false', and 'sspi', which is equivalent to 'true'.

Max Pool Size

100

The maximum number of connections allowed in the pool.

Min Pool Size

0

The minimum number of connections allowed in the pool.

Network Library
-or-
Net

'dbmssocn'

The network library used to establish a connection to an instance of SQL Server. Supported values include dbnmpntw (Named Pipes), dbmsrpcn (Multiprotocol), dbmsadsn (Apple Talk), dbmsgnet (VIA), dbmsipcn (Shared Memory) and dbmsspxn (IPX/SPX), and dbmssocn (TCP/IP).
The corresponding network DLL must be installed on the system to which you connect. If you do not specify a network and you use a local server (for example, "." or "(local)"), shared memory is used.

Packet Size

8192

Size in bytes of the network packets used to communicate with an instance of SQL Server.

Password
-or-
Pwd

 

The password for the SQL Server account logging on.

Persist Security Info

'false'

When set to 'false', security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Resetting the connection string resets all connection string values including the password.

Pooling

'true'

When true, the SQLConnection object is drawn from the appropriate pool, or if necessary, is created and added to the appropriate pool.

User ID

 

The SQL Server login account.

Workstation ID

the local computer name

The name of the workstation connecting to SQL Server.



      • Note
        Use ; to separate each property.
        If a name occurs more than once, the value from the last one in the connection string will be used.
        If you are building your connection string in your app using values from user input fields, make sure the user can't change the connection string by inserting an additional property with another value within the user value.

   SQL Server 2005

  •  SQL Native Client ODBC Driver




    •  Standard security:

"Driver={SQL Native Client};Server=Aron1;Database=pubs;UID=sa;PWD=asdasd;"

 

    •  Trusted connection:

"Driver={SQL Native Client};Server=Aron1;Database=pubs;Trusted_Connection=yes;"

Equivalents
Integrated Security=SSPI equals Trusted_Connection=yes

    •  Prompt for username and password:

oConn.Properties("Prompt") = adPromptAlways
oConn.Open "Driver={SQL Native Client};Server=Aron1;DataBase=pubs;"

 

    •  Enabling MARS (multiple active result sets):

"Driver={SQL Native Client};Server=Aron1;Database=pubs;Trusted_Connection=yes;MARS_Connection=yes"

Equivalents
MultipleActiveResultSets=true equals MARS_Connection=yes

Using MARS with SQL Native Client, by Chris Lee >>

    •  Encrypt data sent over network:

"Driver={SQL Native Client};Server=Aron1;Database=pubs;Trusted_Connection=yes;Encrypt=yes"

 

    •  Attach a database file on connect to a local SQL Server Express instance:

"Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;"
   - or -
"Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;"
   (use |DataDirectory| when your database file resides in the data directory)

Why is the "Database" parameter needed? Answer: If the database was previously attached, SQL Server does not reattach it (it uses the attached database as the default for the connection).

Download the SQL Native Client here >> (the package contains booth the ODBC driver and the OLE DB provider)

Using SQL Server 2005 Express? Don't miss the server name syntax: SERVERNAME\SQLEXPRESS (Substitute "SERVERNAME" with the name of the computer)

  •  SQL Native Client OLE DB Provider




    •  Standard security:

"Provider=SQLNCLI;Server=Aron1;Database=pubs;UID=sa;PWD=asdasd;"

 

    •  Trusted connection:

"Provider=SQLNCLI;Server=Aron1;Database=pubs;Trusted_Connection=yes;"

Equivalents
Integrated Security=SSPI equals Trusted_Connection=yes

    •  Prompt for username and password:

oConn.Properties("Prompt") = adPromptAlways
oConn.Open "Provider=SQLNCLI;Server=Aron1;DataBase=pubs;"

 

    •  Enabling MARS (multiple active result sets):

"Provider=SQLNCLI;Server=Aron1;Database=pubs;Trusted_Connection=yes;MarsConn=yes"

Equivalents
MarsConn=yes equals MultipleActiveResultSets=true equals MARS_Connection=yes

Using MARS with SQL Native Client, by Chris Lee >>

    •  Encrypt data sent over network:

"Provider=SQLNCLI;Server=Aron1;Database=pubs;Trusted_Connection=yes;Encrypt=yes"

 

    •  Attach a database file on connect to a local SQL Server Express instance:

"Provider=SQLNCLI;Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;"
   - or -
"Provider=SQLNCLI;Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;"
   (use |DataDirectory| when your database file resides in the data directory)

Why is the "Database" parameter needed? Answer: If the database was previously attached, SQL Server does not reattach it (it uses the attached database as the default for the connection).

Download the SQL Native Client here >> (the package contains booth the ODBC driver and the OLE DB provider)

Using SQL Server 2005 Express? Don't miss the server name syntax: SERVERNAME\SQLEXPRESS (Substitute "SERVERNAME" with the name of the computer)

  •  SqlConnection (.NET)




    •  Standard Security:

"Data Source=Aron1;Initial Catalog=pubs;User Id=sa;Password=asdasd;"
   - or -
"Server=Aron1;Database=pubs;User ID=sa;Password=asdasd;Trusted_Connection=False"
   (both connection strings produces the same result)

 

    •  Trusted Connection:

"Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;"
   - or -
"Server=Aron1;Database=pubs;Trusted_Connection=True;"
   (both connection strings produces the same result)

(use serverName\instanceName as Data Source to use an specifik SQLServer instance)

    •  Connect via an IP address:
      "Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;"

(DBMSSOCN=TCP/IP instead of Named Pipes, at the end of the Data Source is the port to use (1433 is the default))

    •  Enabling MARS (multiple active result sets):

"Server=Aron1;Database=pubs;Trusted_Connection=True;MultipleActiveResultSets=true"

Note! Use ADO.NET 2.0 for MARS functionality. MARS is not supported in ADO.NET 1.0 nor ADO.NET 1.1

Streamline your Data Connections by Moving to MARS, by Laurence Moroney, DevX.com >>

    •  Attach a database file on connect to a local SQL Server Express instance:

"Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;Database=dbname;Database=dbname;Trusted_Connection=Yes;"
   - or -
"Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;"
   (use |DataDirectory| when your database file resides in the data directory)

Why is the "Database" parameter needed? Answer: If the database was previously attached, SQL Server does not reattach it (it uses the attached database as the default for the connection).

    •  Using "User Instance" on a local SQL Server Express instance:

"Data Source=.\SQLExpress;integrated security=true;attachdbfilename=|DataDirectory|\mydb.mdf;user instance=true;"

The "User Instance" functionality creates a new SQL Server instance on the fly during connect. This works only on a local SQL Server 2005 instance and only when connecting using windows authentication over local named pipes. The purpose is to be able to create a full rights SQL Server instance to a user with limited administrative rights on the computer. To enable the functionality: sp_configure 'user instances enabled','1' (0 to disable)

Using SQL Server 2005 Express? Don't miss the server name syntax: SERVERNAME\SQLEXPRESS (Substitute "SERVERNAME" with the name of the computer)

  •  Context Connection - connecting to "self" from within your CLR stored prodedure/function




    •  C#:

using(SqlConnection connection = new SqlConnection("context connection=true"))
{
    connection.Open();
    // Use the connection
}

 

    •  Visual Basic:

Using connection as new SqlConnection("context connection=true")
    connection.Open()
    ' Use the connection
End Using

 

The context connection lets you execute Transact-SQL statements in the same context (connection) that your code was invoked in the first place.

  •  Read more




    •  When to use SQL Native Client?
      •  .Net applications

Do not use the SQL Native Client. Use the .NET Framework Data Provider for SQL Server (SqlConnection).

      •  COM applications, all other then .Net applications

Use the SQL Native Client if you are accessing an SQL Server 2005 and need the new features of SQL Server 2005 such as MARS, encryption, XML data type etc. Continue use your current provider (OLE DB / ODBC through the MDAC package) if you are not connecting to an SQL Server 2005 (that's quite obvious eh..) or if you are connecting to an SQL Server 2005 but are not using any of the new SQL Server 2005 features.

For more details on the differences between MDAC and SQL Native Client, read this msdn article >>

   Access

  •  ODBC




    •  Standard Security:

"Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\mydatabase.mdb;Uid=Admin;Pwd=;"

 

    •  Workgroup:

"Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\mydatabase.mdb;SystemDB=C:\mydatabase.mdw;"

 

    •  Exclusive:

"Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\mydatabase.mdb;Exclusive=1;Uid=admin;Pwd="

 

  •  OLE DB, OleDbConnection (.NET)




    •  Standard security:

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;User Id=admin;Password=;"

 

    •  Workgroup (system database):

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;Jet OLEDB:System Database=system.mdw;"

 

    •  With password:

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;Jet OLEDB:Database Password=MyDbPassword;"

 

   Oracle

  •  ODBC




    •  New version:

"Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=Username;Pwd=asdasd;"

 

    •  Old version:

"Driver={Microsoft ODBC Driver for Oracle};ConnectString=OracleServer.world;Uid=myUsername;Pwd=myPassword;"

 

  •  OLE DB, OleDbConnection (.NET)




    •  Standard security:

"Provider=msdaora;Data Source=MyOracleDB;User Id=UserName;Password=asdasd;"

This one's from Microsoft, the following are from Oracle

    •  Standard Security:

"Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;User Id=Username;Password=asdasd;"

 

    •  Trusted Connection:

"Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;OSAuthent=1;"

 

  •  OracleConnection (.NET)




    •  Standard:

"Data Source=MyOracleDB;Integrated Security=yes;"

This one works only with Oracle 8i release 3 or later

    •  Specifying username and password:

"Data Source=MyOracleDB;User Id=username;Password=passwd;Integrated Security=no;"

This one works only with Oracle 8i release 3 or later

    •  Declare the OracleConnection:

C#:
using System.Data.OracleClient;
OracleConnection oOracleConn = new OracleConnection();
oOracleConn.ConnectionString = "my connection string";
oOracleConn.Open();

 

VB.NET:
Imports System.Data.OracleClient
Dim oOracleConn As OracleConnection = New OracleConnection()
oOracleConn.ConnectionString = "my connection string"
oOracleConn.Open()

Missing the System.Data.OracleClient namespace? Download .NET Managed Provider for Oracle >>

Great article! "Features of Oracle Data Provider for .NET" by Rama Mohan G. at C# Corner

  •  Core Labs OraDirect (.NET)




    •  Standard:
      "User ID=scott; Password=tiger; Host=ora; Pooling=true; Min Pool Size=0;Max Pool Size=100; Connection Lifetime=0"

Read more at Core Lab and the product page.

  •  Data Shape




    •  MS Data Shape:
      "Provider=MSDataShape.1;Persist Security Info=False;Data Provider=MSDAORA;Data Source=orac;user id=username;password=mypw"

Want to learn data shaping? Check out 4GuyfFromRolla's great article about Data Shaping >>

   MySQL

  •  MyODBC




    •  MyODBC 2.50 Local database:

"Driver={mySQL};Server=localhost;Option=16834;Database=mydatabase;"

 

    •  MyODBC 2.50 Remote database:

"Driver={mySQL};Server=data.domain.com;Port=3306;Option=131072;Stmt=;Database=my-database;Uid=username;Pwd=password;"

 

    •  MyODBC 3.51 Local database:

"DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;DATABASE=myDatabase;USER=myUsername;PASSWORD=myPassword;OPTION=3;"

 

    •  MyODBC 3.51 Remote database:

"DRIVER={MySQL ODBC 3.51 Driver};SERVER=data.domain.com;PORT=3306;DATABASE=myDatabase; USER=myUsername;PASSWORD=myPassword;OPTION=3;"

 

  •  OLE DB, OleDbConnection (.NET)




    •  Standard:

"Provider=MySQLProv;Data Source=mydb;User Id=UserName;Password=asdasd;"

  •  Connector/Net 1.0 (.NET)




    •  Standard:

"Server=Server;Database=Test;Uid=UserName;Pwd=asdasd;"

Download the driver at MySQL Developer Zone.

    •  Specifying port:

"Server=Server;Port=1234;Database=Test;Uid=UserName;Pwd=asdasd;"

Default port is 3306. Enter value -1 to use a named pipe connection.

    •  Declare the MySqlClient connection:

C#:
using MySql.Data.MySqlClient;
MySqlConnection oMySqlConn = new MySqlConnection();
oMySqlConn.ConnectionString = "Server=Server;Database=Test;Uid=UserName;Pwd=asdasd;";
oMySqlConn.Open();

 

VB.NET:
Imports MySql.Data.MySqlClient
Dim oMySqlConn As MySqlConnection = New MySqlConnection()
oMySqlConn.ConnectionString = "Server=Server;Database=Test;Uid=UserName;Pwd=asdasd;"
oMySqlConn.Open()

  •  MySqlConnection (.NET)




    •  eInfoDesigns.dbProvider:

"Data Source=server;Database=mydb;User ID=username;Password=pwd;Command Logging=false"

This one is used with eInfoDesigns dbProvider, an add-on to .NET

    •  Declare the MySqlConnection:

C#:
using eInfoDesigns.dbProvider.MySqlClient;
MySqlConnection oMySqlConn = new MySqlConnection();
oMySqlConn.ConnectionString = "my connection string";
oMySqlConn.Open();

 

VB.NET:
Imports eInfoDesigns.dbProvider.MySqlClient
Dim oMySqlConn As MySqlConnection = New MySqlConnection()
oMySqlConn.ConnectionString = "my connection string"
oMySqlConn.Open()

  •  SevenObjects MySqlClient (.NET)




    •  Standard:

"Host=server; UserName=myusername; Password=mypassword;Database=mydb;"

This is a freeware ADO.Net data provider from SevenObjects

  •  Core Labs MySQLDirect (.NET)




    •  Standard:

"User ID=root; Password=pwd; Host=localhost; Port=3306; Database=test;Direct=true; Protocol=TCP; Compress=false; Pooling=true; Min Pool Size=0;Max Pool Size=100; Connection Lifetime=0"

Read more at Core Lab and the product page.

   Interbase

  •  ODBC, Easysoft




    •  Local computer:

"Driver={Easysoft IB6 ODBC};Server=localhost;Database=localhost:C:\mydatabase.gdb;Uid=username;Pwd=password"

 

    •  Remote Computer:

"Driver={Easysoft IB6 ODBC};Server=ComputerName;Database=ComputerName:C:\mydatabase.gdb;Uid=username;Pwd=password"

Read more about this driver: Easysoft ODBC-Interbase driver >>

  •  ODBC, Intersolv




    •  Local computer:

"Driver={INTERSOLV InterBase ODBC Driver (*.gdb)};Server=localhost;Database=localhost:C:\mydatabase.gdb;Uid=username;Pwd=password"

 

    •  Remote Computer:

"Driver={INTERSOLV InterBase ODBC Driver (*.gdb)};Server=ComputerName;Database=ComputerName:C:\mydatabase.gdb;Uid=username;Pwd=password"

This driver are provided by DataDirect Technologies >> (formerly Intersolv)

 

  •  OLE DB, SIBPROvider




    •  Standard:

"provider=sibprovider;location=localhost:;data source=c:\databases\gdbs\mygdb.gdb;user id=SYSDBA;password=masterkey"

 

    •  Specifying character set:

"provider=sibprovider;location=localhost:;data source=c:\databases\gdbs\mygdb.gdb;user id=SYSDBA;password=masterkey;character set=ISO8859_1"

 

    •  Specifying role:

"provider=sibprovider;location=localhost:;data source=c:\databases\gdbs\mygdb.gdb;user id=SYSDBA;password=masterkey;role=DIGITADORES"

Read more about SIBPROvider >>

 


Read more about connecting to Interbase in this Borland Developer Network article http://community.borland.com/article/0,1410,27152,00.html


   IBM DB2

  •  OLE DB, OleDbConnection (.NET) from ms




    •  TCP/IP:

"Provider=DB2OLEDB;Network Transport Library=TCPIP;Network Address=XXX.XXX.XXX.XXX;Initial Catalog=MyCtlg;Package Collection=MyPkgCol;Default Schema=Schema;User ID=MyUser;Password=MyPW"

 

    •  APPC:

"Provider=DB2OLEDB;APPC Local LU Alias=MyAlias;APPC Remote LU Alias=MyRemote;Initial Catalog=MyCtlg;Package Collection=MyPkgCol;Default Schema=Schema;User ID=MyUser;Password=MyPW"

 

  •  IBM's OLE DB Provider (shipped with IBM DB2 UDB v7 or above)




    •  TCP/IP:

Provider=IBMDADB2;Database=sample;HOSTNAME=db2host;PROTOCOL=TCPIP;PORT=50000;uid=myUserName;pwd=myPwd;

 

  •  ODBC




    •  Standard:

"driver={IBM DB2 ODBC DRIVER};Database=myDbName;hostname=myServerName;port=myPortNum;protocol=TCPIP; uid=myUserName; pwd=myPwd"

 

   Sybase

  •  ODBC




    •  Standard Sybase System 12 (or 12.5) Enterprise Open Client:

"Driver={SYBASE ASE ODBC Driver};Srvr=Aron1;Uid=username;Pwd=password"

 

    •  Standard Sybase System 11:

"Driver={SYBASE SYSTEM 11};Srvr=Aron1;Uid=username;Pwd=password;Database=mydb"

For more information check out the Adaptive Server Enterprise Document Sets

    •  Intersolv 3.10:

"Driver={INTERSOLV 3.10 32-BIT Sybase};Srvr=Aron1;Uid=username;Pwd=password;"

 

    •  Sybase SQL Anywhere (former Watcom SQL ODBC driver):

"ODBC; Driver=Sybase SQL Anywhere 5.0; DefaultDir=c:\dbfolder\;Dbf=c:\mydatabase.db;Uid=username;Pwd=password;Dsn="""""

Note! The two double quota following the DSN parameter at the end are escaped quotas (VB syntax), you may have to change this to your language specific escape syntax. The empty DSN parameter is indeed critical as not including it will result in error 7778.

Read more in the Sybase SQL Anywhere User Guide (see part 3, chapter 13) >>

  •  OLE DB




    •  Adaptive Server Anywhere (ASA):

"Provider=ASAProv;Data source=myASA"

Read more in the ASA User Guide (part 1, chapter 2) >>

    •  Adaptive Server Enterprise (ASE) with Data Source .IDS file:

"Provider=Sybase ASE OLE DB Provider; Data source=myASE"

Note that you must create a Data Source .IDS file using the Sybase Data Administrator. These .IDS files resemble ODBC DSNs.

    •  Adaptive Server Enterprise (ASE):

"Provider=Sybase.ASEOLEDBProvider;Srvr=myASEserver,5000;Catalog=myDBname;User Id=username;Password=password"
   - some reports on problem using the above one, try the following as an alternative -

"Provider=Sybase.ASEOLEDBProvider;Server Name=myASEserver,5000;Initial Catalog=myDBname;User Id=username;Password=password"

This one works only from Open Client 12.5 where the server port number feature works,?allowing fully qualified connection strings to be used without defining?any .IDS Data Source files.

  •  AseConnection (.NET)




    •  Standard:

"Data Source='myASEserver';Port=5000;Database='myDBname';UID='username';PWD='password';"

 

    •  Declare the AseConnection:

C#:
using Sybase.Data.AseClient;
AseConnection oCon = new AseConnection();
oCon.ConnectionString="my connection string";
oCon.Open();

 

VB.NET:
Imports System.Data.AseClient
Dim oCon As AseConnection = New AseConnection()
oCon.ConnectionString="my connection string"
oCon.Open()

Read more! Adaptive Server Enterprise ADO.NET Data Provider Documentation >>

   Informix

  •  ODBC




    •  Informix 3.30:

"Dsn='';Driver={INFORMIX 3.30 32 BIT};Host=hostname;Server=myserver;Service=service-name;Protocol=olsoctcp;Database=mydb;UID=username;PWD=myPwd

 

    •  Informix-CLI 2.5:

"Driver={Informix-CLI 2.5 (32 Bit)};Server=myserver;Database=mydb;Uid=username;Pwd=myPwd"

 

  •  OLE DB




    •  IBM Informix OLE DB Provider:

"Provider=Ifxoledbc.2;password=myPw;User ID=myUser;Data Source=dbName@serverName;Persist Security Info=true"

 

   Ingres

  •  ODBC




    • DSN-less

"Provider=MSDASQL.1;DRIVER=Ingres;SRVR=xxxxx;DB=xxxxx;Persist Security Info=False;uid=xxxx;pwd=xxxxx;SELECTLOOPS=N;Extended Properties="""SERVER=xxxxx;DATABASE=xxxxx;SERVERTYPE=INGRES""

 

   Mimer SQL

  •  ODBC




    •  Standard Security:

"Driver={MIMER};Database=mydb;Uid=myuser;Pwd=mypw;"

 

    •  Prompt for username and password:

"Driver={MIMER};Database=mydb;"

 

   Lightbase

  •  Standard




    •  Standard:

"user=USERLOGIN;password=PASSWORD;UDB=USERBASE;server=SERVERNAME"

 

   PostgreSQL

  •  Core Labs PostgreSQLDirect (.NET)




    •  Standard:

"User ID=root; Password=pwd; Host=localhost; Port=5432; Database=testdb;Pooling=true; Min Pool Size=0; Max Pool Size=100; Connection Lifetime=0"

Read more at Core Lab and the product page.

 

  •  PostgreSQL driver




    •  Standard:

"DRIVER={PostgreSQL};SERVER=ipaddress;port=5432;DATABASE=dbname;UID=username;PWD=password;"

 

  •  Npgsql by pgFoundry (.NET)




    •  SSL activated:

"Server=127.0.0.1;Port=5432;Userid=myuserid;password=mypw;Protocol=3;SSL=true;Pooling=true;MinPoolSize=3;MaxPoolSize=20;Encoding=UNICODE;Timeout=20;SslMode=Require"



 Without SSL:

"Server=127.0.0.1;Port=5432;Userid=myuserid;password=mypw;Protocol=3;SSL=false;Pooling=true;MinPoolSize=1;MaxPoolSize=20;Encoding=UNICODE;Timeout=15;SslMode=Disable"

Read more in the Npgsql: User's Manual and on the pgFoundry website.

 

   Paradox

  •  ODBC




    •  5.X:

Driver={Microsoft Paradox Driver (*.db )};DriverID=538;Fil=Paradox 5.X;DefaultDir=c:\pathToDb\;Dbq=c:\pathToDb\;CollatingSequence=ASCII"

 

    •  7.X:

"Provider=MSDASQL.1;Persist Security Info=False;Mode=Read;Extended Properties='DSN=Paradox;DBQ=C:\myDb;DefaultDir=C:\myDb;DriverId=538;FIL=Paradox 7.X;MaxBufferSize=2048;PageTimeout=600;';Initial Catalog=C:\myDb"

 

  •  OleDbConnection (.NET)




    •  Standard

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\myDb;Extended Properties=Paradox 5.x;"

MS kb-article: How to use Paradox data with Access and Jet >>

 

   DSN

  •  ODBC




    •  DSN:

"DSN=myDsn;Uid=username;Pwd=;"

 

    •  File DSN:

"FILEDSN=c:\myData.dsn;Uid=username;Pwd=;"

 

   Firebird

  •  ODBC - IBPhoenix Open Source




    •  Standard:

"DRIVER=Firebird/InterBase(r) driver;UID=SYSDBA;PWD=masterkey;DBNAME=D:\FIREBIRD\examples\TEST.FDB"

IBPhoenix ODBC; More info, download etc >>

  •  .NET - Firebird .Net Data Provider




    •  Standard:

"User=SYSDBA;Password=masterkey;Database=SampleDatabase.fdb;DataSource=localhost;Port=3050;Dialect=3;Charset=NONE;Role=;Connection lifetime=15;Pooling=true;MinPoolSize=0;MaxPoolSize=50;Packet Size=8192;ServerType=0"

Firebird ADO.NET project >>

Firebird ADO.NET downloads >>

   Excel

  •  ODBC




    •  Standard:

"Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=C:\MyExcel.xls;DefaultDir=c:\mypath;"

TIP! SQL syntax: "SELECT * FROM [sheet1$]" - i.e. worksheet name followed by a "$" and wrapped in "[" "]" brackets.

  •  OLE DB




    •  Standard:

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"""

"HDR=Yes;" indicates that the first row contains columnnames, not data

"IMEX=1;" tells the driver to always read "intermixed" data columns as text

TIP! SQL syntax: "SELECT * FROM [sheet1$]" - i.e. worksheet name followed by a "$" and wrapped in "[" "]" brackets.

   Text

  •  ODBC




    •  Standard:

"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=c:\txtFilesFolder\;Extensions=asc,csv,tab,txt;"

 

  •  OLE DB




    •  Standard:

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\txtFilesFolder\;Extended Properties=""text;HDR=Yes;FMT=Delimited"""

"HDR=Yes;" indicates that the first row contains columnnames, not data

   DBF / FoxPro

  •  ODBC




    •  standard:

"Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=c:\mydbpath;"

 

  •  OLE DB, OleDbConnection (.NET)




    •  standard:

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\folder;Extended Properties=dBASE IV;User ID=Admin;Password="

 

   AS/400 (iSeries)

  •  OLE DB, OleDbConnection (.NET)




    •  IBM Client Access OLE DB provider:

"PROVIDER=IBMDA400; DATA SOURCE=MY_SYSTEM_NAME;USER ID=myUserName;PASSWORD=myPwd"

Where MY_SYSTEM_NAME is the name given to the system connection in OperationsNavigator

    •  IBM Client Access OLE DB provider:

"PROVIDER=IBMDA400; DATA SOURCE=MY_SYSTEM_NAME;USER ID=myUserName;PASSWORD=myPwd;DEFAULT COLLECTION=MY_LIBRARY;"

Where MY_SYSTEM_NAME is the name given to the System Connection, and MY_LIBRARY is the name given to the library in iSeries Navigator.

  •  ODBC




    •  IBM Client Access ODBC driver:

"Driver={Client Access ODBC Driver (32-bit)};System=my_system_name;Uid=myUserName;Pwd=myPwd"

   Exchange

  •  OLE DB




    •  Exchange OLE DB provider:

"ExOLEDB.DataSource"

Specify store in the connection open command like this: conn.open "http://servername/mypublicstore"

Check out
this article at msdn >>
and this one at Addison-Wesley >>

   Visual FoxPro

  •  OLE DB, OleDbConnection (.NET)




    •  Database container (.DBC):

"Provider=vfpoledb.1;Data Source=C:\MyDbFolder\MyDbContainer.dbc;Collating Sequence=machine"

 

    •  Free table directory:

"Provider=vfpoledb.1;Data Source=C:\MyDataDirectory\;Collating Sequence=general"

 

    •  Force the provider to use an ODBC DSN:

""Provider=vfpoledb.1;DSN=MyDSN""

Read more (Microsoft msdn) >>

  •  ODBC




    •  Database container (.DBC):

"Driver={Microsoft Visual FoxPro Driver};SourceType=DBC;SourceDB=c:\myvfpdb.dbc;Exclusive=No;NULL=NO;Collate=Machine;BACKGROUNDFETCH=NO;DELETED=NO"

 

    •  Free Table directory:

"Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=c:\myvfpdbfolder;Exclusive=No;Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO"

"Collate=Machine" is the default setting, for other settings check the list of supported collating sequences >>


Microsoft Visual Foxpro site: http://msdn.microsoft.com/vfoxpro


   Pervasive

  •  ODBC




    •  Standard:

"Driver={Pervasive ODBC Client Interface};ServerName=srvname;dbq=@dbname"

Pervasive ODBC info >>

  •  OLE DB




    •  Standard:

"Provider=PervasiveOLEDB;Data Source=C:\path"

Pervasive OLE DB info >>

   UDL

  •  UDL




    •  UDL:

"File Name=c:\myDataLink.udl;"

 

2008年1月11日星期五

MsFlexGrid使用总结

最近看到我们群里和论坛里关于MsFlexGrid的讨论很多,搜集了一点这方面的资料供大家参考.大家可以继续添加

VB
MsFlexGrid控件的使用细则(收集)

>>
将文本赋值给MsFlexGrid的单元格
MsFlexGrid.TextMatrix(3,1)="Hello"

>>
MsFlexGrid控件单元格中插入背景图形
Set MsFlexGrid.CellPicture=LoadPicture("C:\temp\1.bmp")

>>
选中某个单元
MsFlexGrid.Row=1
MsFlexGrid.Col=1

>>
用粗体格式化当前选中单元
MsFlexGrid.CellFontBold=True

>>
添加新的一行
使用AddItem方法,Tab字符分开不同单元格的内容
dim row as string
row="AAA"&vbtab&"bbb"
MsFlexFrid1.addItem row

>>
怎样来实现MSFlexGrid控件单数行背景为白色,双数的行背景为蓝色?
Dim i As Integer
With MSFlexGrid1
.AllowBigSelection = True '
设置网格样式
.FillStyle = flexFillRepeat
For i = 0 To .Rows - 1
.Row = i: .Col = .FixedCols
.ColSel = .Cols() - .FixedCols - 1
If i Mod 2 = 0 Then
.CellBackColor = &HC0C0C0 '
浅灰
Else
.CellBackColor = vbBlue '
兰色
End If
Next i
End With

>> MSFlexGrid
控件如何移到最后一行
MSFlexGrid1.TopRow = MSFlexGrid1.Rows � 1

>>
如何判断msflexgrid有无滚动条
Declare Function GetScrollRange Lib "user32" (ByVal hWnd As Long, ByVal nBar As Long, lpMinPos As

Long, lpMaxPos As Long) As Long
Public Const SB_HORZ = &H0
Public Const SB_VERT = &H1

Public Function VsScroll(MshGrid As MSHFlexGrid) As Boolean '
判断水平滚动条的可见性
Dim i As Long
VsScroll = False
i = GetScrollRange(MshGrid.hWnd, SB_HORZ, lpMinPos, lpMaxPos)
If lpMaxPos <> lpMinPos Then VsScroll = True
End Function

Public Function HeScroll(MshGrid As MSHFlexGrid) As Boolean '
判断垂直滚动条的可见性
Dim i As Long
HeScroll = False
i = GetScrollRange(MshGrid.hWnd, SB_VERT, lpMinPos, lpMaxPos)
If lpMaxPos <> lpMinPos Then HeScroll = True
End Function

>>
程序运行时,想动态增加MSFlexgrid的列数
在第2列后插入一列:
Private Sub Form_Load()
Me.MSHFlexGrid1.Cols = 5
MSHFlexGrid1.Rows = 2
For i = 0 To Me.MSHFlexGrid1.Cols - 1
Me.MSHFlexGrid1.TextMatrix(0, i) = i
Me.MSHFlexGrid1.TextMatrix(1, i) = i
Next
End Sub

Private Sub Command1_Click()
Me.MSHFlexGrid1.Cols = Me.MSHFlexGrid1.Cols + 1
Me.MSHFlexGrid1.ColPosition(5) = 3
End Sub

>>
请教MSFlexGrid中的对齐功能的使用
设置MSFlexGrid1.ColAlignment(index)=n


>>
得到MSFlexGrid控件中当前选中的一行
msflexgrid1.rowsel
就是当前选中行

>>
如何通过代码调节列宽度
msflexgrid1.colwidth(i)=4000
MsFlexGrid控件的内容输出到文本

'OutDataToText
'
MsFlexGrid控件中显示的内容输出到文本文件
Public Sub OutDataToText(Flex As MSFlexGrid)
Dim s As String
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim strTemp As String
On Error GoTo Ert
Me.MousePointer = 11
On Error Resume Next
DoEvents
Dim FileNum As Integer
FileNum = FreeFile
Open "d:aa.txt" For Output As #FileNum
With Flex
k = .Rows
For i = 0 To k - 1
strTemp = ""
For j = 0 To .Cols - 1
DoEvents
strTemp = strTemp & .TextMatrix(i, j) & ","
Next j
Print #FileNum, Left(strTemp, Len(strTemp) - 1)
Next i
End With
Close #FileNum
Me.MousePointer = 0
MsgBox "
导出成功"
Ert:
MsgBox Err.Description
Me.MousePointer = 0
End Sub

增加 MsFlexGrid 的编辑功能
概述
MsFlexGrid
控件没有提供文本编辑的功能,下面的例子演示了如何利用一个TextBox 实现编辑当前网格的功能.在按下一个键后, 就把TextBox 移动到当前的位置, 并激活。 在键入回车或移动到其他网格时,就把TextBox 中的内容放到网格中。

实现步骤
1
打开 VB5 开启一个新的工程。
2
在菜单"工程" 中选择 "部件" 在列表中选中 "Microsoft FlexGrid Control .."
3
放一个 MsFlexGrid 控件和一个TextBox 控件(Text1) Form1 修改MsFlexGrid 控件的名称为 Grid1 设置Grid1 的行,列 4 固定行,列为 0 设置 Text1 Visiable False BorderStyle None(0)
4
Form1 的代码中增加声明:

Const ASC_ENTER = 13 '
回车
Dim gRow As Integer
Dim gCol As Integer

5
增加代码到 Grid_KeyPress 过程:

Private Sub Grid1_KeyPress(KeyAscii As Integer)
' Move the text box to the current grid cell:
Text1.Top = Grid1.CellTop + Grid1.Top
Text1.Left = Grid1.CellLeft + Grid1.Left
' Save the position of the grids Row and Col for later:
gRow = Grid1.Row
gCol = Grid1.Col
' Make text box same size as current grid cell:
Text1.Width = Grid1.CellWidth - 2 * Screen.TwipsPerPixelX
Text1.Height = Grid1.CellHeight - 2 * Screen.TwipsPerPixelY
' Transfer the grid cell text:
Text1.Text = Grid1.Text
' Show the text box:
Text1.Visible = True
Text1.ZOrder 0 '
Text1 放到最前面!
Text1.SetFocus
' Redirect this KeyPress event to the text box:
If KeyAscii <> ASC_ENTER Then
SendKeys Chr$(KeyAscii)
End If
End Sub

6
增加代码到 Text1_KeyPress 过程:

Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = ASC_ENTER Then
Grid1.SetFocus ' Set focus back to grid, see Text_LostFocus.
KeyAscii = 0 ' Ignore this KeyPress.
End If
End Sub

7
增加代码到 Text1_LostFocus 过程:

Private Sub Text1_LostFocus()
Dim tmpRow As Integer
Dim tmpCol As Integer
' Save current settings of Grid Row and col.
This is needed only if
' the focus is set somewhere else in the Grid.
tmpRow = Grid1.Row
tmpCol = Grid1.Col
' Set Row and Col back to what they were before Text1_LostFocus:
Grid1.Row = gRow
Grid1.Col = gCol
Grid1.Text = Text1.Text ' Transfer text back to grid.
Text1.SelStart = 0 ' Return caret to beginning.
Text1.Visible = False ' Disable text box.
' Return row and Col contents:
Grid1.Row = tmpRow
Grid1.Col = tmpCol
End Sub

8
好了。 F5 开始测试。 您可以自由地在 Grid 中移动, 按回车可以开始或结束编辑。



使用MsFlexGrid控件的几个函数

VB处理数据显示的时候,使用表格是一种好的方法,虽然DataGrid可以与数据源绑定,但是总有美中不足,就是外观不好看,所以有时应用MsFlexGrid显示数据还是一种比较好的方法,以下几个函数是用来控制MsFlexGrid的程序

(
本人语言表达能力有限,还请见谅)

''MsFlexGrid操作函数

''
合并列
Public Function MergeCol(GridObj As Object, ByVal StartCol As Long, ByVal EndCol As Long, ByVal ColValue As String, ByVal CurrentRow As Long) As Boolean
If StartCol > EndCol Or StartCol > GridObj.Cols Or CurrentRow > GridObj.Rows Then
MsgBox "
对不起,行列设置错误!", vbOKOnly, App.Title
MergeCol = False
Exit Function
End If

For I = StartCol To EndCol
GridObj.MergeCol(I) = True
GridObj.TextArray(faIndex(GridObj, CurrentRow, I)) = ColValue
GridObj.ColAlignment(I) = flexAlignCenterCenter
Next I


GridObj.MergeRow(CurrentRow) = True

MergeCol = True

End Function

''
合并行
Public Function MergeRow(GridObj As Object, ByVal StartRow As Long, ByVal EndRow As Long, ByVal RowValue As String, ByVal CurrentCol As Long) As Boolean
If StartRow > EndRow Or StartRow > GridObj.Rows Or CurrentCol > GridObj.Cols Then
MsgBox "
对不起,行列设置错误!", vbOKOnly, App.Title
MergeRow = False
Exit Function
End If

For I = StartRow To EndRow
GridObj.MergeRow(I) = True
GridObj.TextArray(faIndex(GridObj, I, CurrentCol)) = RowValue
GridObj.ColAlignment(CurrentCol) = flexAlignCenterCenter

Next I
GridObj.MergeCol(CurrentCol) = True
MergeRow = True

End Function

''
转换索引
Public Function faIndex(GridObj As Object, ByVal row As Integer, ByVal col As Integer) As Long
If row > GridObj.Rows Or row < 0 Or col > GridObj.Cols Or col < 0 Then
MsgBox "
对不起,行列设置错误!", vbOKOnly, App.Title
faIndex = -1

Exit Function
End If

faIndex = row * GridObj.Cols + col

End Function


''
插入行
Public Function SetItem(GridObj As Object, ByVal row As Integer, ByVal col As Integer, ByVal

SetValue As String) As Boolean
If row > GridObj.Rows Or row < 0 Or col > GridObj.Cols Or col < 0 Then
MsgBox "
对不起,行列设置错误!", vbOKOnly, App.Title
SetItem = False
Exit Function
End If
GridObj.TextArray(faIndex(GridObj, row, col)) = SetValue

SetItem = True
End Function

''
得到单元格值
Public Function GetItem(GridObj As Object, ByVal row As Integer, ByVal col As Integer) As String

If row > GridObj.Rows Or row < 0 Or col > GridObj.Cols Or col < 0 Then
MsgBox "
对不起,行列设置错误!", vbOKOnly, App.Title
GetItem = ""
Exit Function
End If
GetItem = GridObj.TextArray(faIndex(GridObj, row, col))
End Function

msflexgrid控件中每一个cell格的内容是不可以由用户直接编辑的但是我们可以通过一些小技巧来方便的实现这编辑功能来扩展msflexgrid的应用(在实际应用中这是很常用的功能)。
你只需按下面的做即可轻松实现编辑msflexgrid控件数据的功能
例在窗体上放一文本框txtvalue,和一msflexgrid控件grid

'
文本框控件的keypress事件
private sub txtvalue_keypress(keyascii as integer)
'
放入一些处理过程,如只需输入数字时的处理

dim i
i=1
end sub

private sub txtvalue_change()
grid.text = txtvalue.text
end sub


'
gridentercell事件中加入下例代码
private sub grid_entercell()
txtvalue.text = grid.text
txtvalue.selstart = 0
txtvalue.sellength = len(txtvalue.text)
end sub

'
当用户输入数据时直接调用文本框的keypress事件
private sub grid_keypress(keyascii as integer)
txtvalue_keypress keyascii
end sub

ok,
这样一个可编辑的msflexgrid控件就完成了,简单吧!!

原理
当用户点击msflexgrid中的某个cell格要输入数据时,产生entercell事件,在这里我们对文本
框进行初始化,输入当前cell格中的内容,并且选中所有文本。当用户要按下按键进行输入时,就直
接调用txtvalue的事件,由文本框来处理.

处理的结果同grid的当前cell同步,使用户编辑cell格就象使用文本框一样方便。

 

如何实现网格单元格中文字的多行显示?

网格单元格中文字的多行显示很简单,只要把WordWarp属性改为True就可以了。

2008年1月9日星期三

【SQL SERVER】SQL数据类型详解

SQL数据类型详解

 (1)二进制数据类型

  二进制数据包括 BinaryVarbinary Image
  Binary 数据类型既可以是固定长度的(Binary),也可以是变长度的。
  Binary[(n)] n 位固定的二进制数据。其中,n 的取值范围是从 1 8000。其存储窨的大小是 n + 4 个字节。
  Varbinary[(n)] n 位变长度的二进制数据。其中,n 的取值范围是从 1 8000。其存储窨的大小是 n + 4个字节,不是n 个字节。
  在 Image 数据类型中存储的数据是以位字符串存储的,不是由 SQL Server 解释的,必须由应用程序来解释。例如,应用程序可以使用BMPTIEFGIF JPEG 格式把数据存储在 Image 数据类型中。

(2)字符数据类型

  字符数据的类型包括 CharVarchar Text
  字符数据是由任何字母、符号和数字任意组合而成的数据。
   Varchar 是变长字符数据,其长度不超过 8KBChar 是定长字符数据,其长度最多为 8KB。超过 8KB ASCII 数据可以使用Text数据类型存储。例如,因为 Html 文档全部都是 ASCII 字符,并且在一般情况下长度超过 8KB,所以这些文档可以 Text 数据类型存储在SQL Server 中。

(3)Unicode 数据类型

  Unicode 数据类型包括 Nchar,Nvarchar Ntext
   在 Microsoft SQL Server 中,传统的非 Unicode 数据类型允许使用由特定字符集定义的字符。在 SQL Server安装过程中,允许选择一种字符集。使用 Unicode 数据类型,列中可以存储任何由Unicode 标准定义的字符。在 Unicode 标准中,包括了以各种字符集定义的全部字符。使用Unicode数据类型,所战胜的窨是使用非 Unicode 数据类型所占用的窨大小的两倍。
  在 SQL Server 中,Unicode 数据以 NcharNvarchar Ntext 数据类型存储。使用这种字符类型存储的列可以存储多个字符集中的字符。当列的长度变化时,应该使用Nvarchar 字符类型,这时最多可以存储 4000 个字符。当列的长度固定不变时,应该使用 Nchar 字符类型,同样,这时最多可以存储4000 个字符。当使用 Ntext 数据类型时,该列可以存储多于 4000 个字符。

(4)日期和时间数据类型

  日期和时间数据类型包括 Datetime Smalldatetime两种类型
   日期和时间数据类型由有效的日期和时间组成。例如,有效的日期和时间数据包括"4/01/98 12:15:00:00:00 PM""1:28:29:15:01AM 8/17/98"。前一个数据类型是日期在前,时间在后一个数据类型是霎时间在前,日期在后。在 Microsoft SQL Server中,日期和时间数据类型包括Datetime Smalldatetime 两种类型时,所存储的日期范围是从 1753 1 1 日开始,到9999 12 31 日结束(每一个值要求 8 个存储字节)。使用 Smalldatetime 数据类型时,所存储的日期范围是 1900 1 1 开始,到 2079 12 31 日结束(每一个值要求 4 个存储字节)
  日期的格式可以设定。设置日期格式的命令如下:
  Set DateFormat {format | @format _var|
  其中,format | @format_var 是日期的顺序。有效的参数包括 MDYDMYYMDYDMMYD DYM。在默认情况下,日期格式为MDY
  例如,当执行 Set DateFormat YMD 之后,日期的格式为年 形式;当执行 Set DateFormat DMY 之后,日期的格式为日 月有年 形式

5)数字数据类型

  数字数据只包含数字。数字数据类型包括正数和负数、小数(浮点数)和整数
  整数由正整数和负整数组成,例如 39250-2 33967。在 Micrsoft SQL Server 中,整数存储的数据类型是    IntSmallint TinyintInt 数据类型存储数据的范围大于 Smallint 数据类型存储数据的范围,而 Smallint 据类型存储数据的范围大于Tinyint 数据类型存储数据的范围。使用 Int 数据狗昔存储数据的范围是从 -2 147 483 648 2 147 483 647(每一个值要求4个字节存储空间)。使用 Smallint 数据类型时,存储数据的范围从 -32 768 32 767(每一个值要求2个字节存储空间)。使用Tinyint 数据类型时,存储数据的范围是从0 255(每一个值要求1个字节存储空间)。
  精确小娄数据在 SQL Server 中的数据类型是 Decimal Numeric。这种数据所占的存储空间根据该数据的位数后的位数来确定。
  在SQL Server 中,近似小数数据的数据类型是 Float Real。例如,三分之一这个分数记作。3333333,当使用近似数据类型时能准确表示。因此,从系统中检索到的数据可能与存储在该列中数据不完全一样。

6)货币数据表示正的或者负的货币数量 。

  在 Microsoft SQL Server 中,货币数据的数据类型是Money Smallmoney

  Money数据类型要求 8 个存储字节,Smallmoney 数据类型要求 4 个存储字节。

7)特殊数据类型

  特殊数据类型包括前面没有提过的数据类型。特殊的数据类型有3种,即    TimestampBit Uniqueidentifier
  Timestamp 用于表示SQL Server 活动的先后顺序,以二进投影的格式表示。Timestamp 数据与插入数据或者日期和时间没有关系。
  Bit 1 或者 0 组成。当表示真或者假、ON 或者 OFF 时,使用 Bit 数据类型。例如,询问是否是每一次访问的客户机请求可以存储在这种数据类型的列中。
  Uniqueidentifier 16 字节的十六进制数字组成,表示一个全局唯一的。当表的记录行要求唯一时,GUID是非常有用。例如,在客户标识号列使用这种数据类型可以区别不同的客户。

2.用户定义的数据类型

   用户定义的数据类型基于在 Microsoft SQL Server 中提供的数据类型。当几个表中必须存储同一种数据类型时,并且为保证这些列有相同的数据类型、长度和可空性时,可以使用用户定义的数据类型。例如,可定义 一种称为   postal_code 的数据类型,它基于 Char 数据类型。
  当创建用户定义的数据类型时,必须提供三个数:数据类型的名称、所基于的系统数据类型和数据类型的可空性。

1)创建用户定义的数据类型

  创建用户定义的数据类型可以使用 Transact-SQL 语句。系统存储过程 sp_addtype 可以来创建用户定义的数据类型。其语法形式如下:
  sp_addtype {type},[,system_data_bype][,'null_type']
   其中,type 是用户定义的数据类型的名称。system_data_type 是系统提供的数据类型,例如 DecimalIntChar   等等。 null_type 表示该数据类型是如何处理空值的,必须使用单引号引起来,例如'NULL''NOT NULL'或者'NONULL'
  例子:
  Use cust
  Exec sp_addtype ssn,'Varchar(11)',"Not Null'
  创建一个用户定义的数据类型 ssn,其基于的系统数据类型是变长为11 的字符,不允许空。
  例子:
  Use cust
  Exec sp_addtype birthday,datetime,'Null'
  创建一个用户定义的数据类型 birthday,其基于的系统数据类型是 DateTime,允许空。
  例子:
  Use master
  Exec sp_addtype telephone,'varchar(24),'Not Null'
  Eexc sp_addtype fax,'varchar(24)','Null'
  创建两个数据类型,即 telephone fax

2)删除用户定义的数据类型

  当用户定义的数据类型不需要时,可删除。删除用户定义的数据类型的命令是 sp_droptype {'type'}
  例子:
  Use master
  Exec sp_droptype 'ssn'
  注意:当表中的列还正在使用用户定义的数据类型时,或者在其上面还绑定有默认或者规则时,这种用户定义的数据类型不能删除。

SQL SERVER的字段类型说明

  以下为SQL SERVER7.0以上版本的字段类型说明。SQL SERVER6.5的字段类型说明请参考SQL SERVER提供的说明。

字段类型

描述

 bit

 01的整型数字

 int

 -2^31(-2,147,483,648)2^31(2,147,483,647)的整型数字

 smallint

 -2^15(-32,768)2^15(32,767)的整型数字

 tinyint

 0255的整型数字

 

 

 decimal

 -10^3810^38-1的定精度与有效位数的数字

 numeric

 decimal的同义词

 

 

 money

 -2^63(-922,337,203,685,477.5808)2^63-1(922,337,203,685,477.5807)的货币数据,最小货币单位千分之十

 smallmoney

 -214,748.3648214,748.3647的货币数据,最小货币单位千分之十

 

 

 float

 -1.79E+3081.79E+308可变精度的数字

 real

 -3.04E+383.04E+38可变精度的数字

 

 

 datetime

 175311日到99991231的日期和时间数据,最小时间单位为百分之三秒或3.33毫秒

 smalldatetime

 190011日到207966日的日期和时间数据,最小时间单位为分钟

 

 

 timestamp

 时间戳,一个数据库宽度的唯一数字

 uniqueidentifier

 全球唯一标识符GUID

 

 

 char

 定长非Unicode的字符型数据,最大长度为8000

 varchar

 变长非Unicode的字符型数据,最大长度为8000

 text

 变长非Unicode的字符型数据,最大长度为2^31-1(2G)

 

 

 nchar

 定长Unicode的字符型数据,最大长度为8000

 nvarchar

 变长Unicode的字符型数据,最大长度为8000

 ntext

 变长Unicode的字符型数据,最大长度为2^31-1(2G)

 

 

 binary

 定长二进制数据,最大长度为8000

 varbinary

 变长二进制数据,最大长度为8000

 image

 变长二进制数据,最大长度为2^31-1(2G)