在本文中,我们将详细介绍如何在SQLServerManagementStudio中将1设置为0'-1关系的各个方面,并为您提供关于sql1=0的相关解答,同时,我们也将为您带来关于c#–在SQLSer
在本文中,我们将详细介绍如何在SQL Server Management Studio中将1设置为0'-1关系的各个方面,并为您提供关于sql 1=0的相关解答,同时,我们也将为您带来关于c# – 在SQL Server Management Studio中创建一个新菜单项、SQL Server Management Studio中'go'附近的语法不正确、SQL Server 在Management Studio中使用Web浏览器、sql-server – SQL Server Management Studio中的“收藏夹”或“宏”?的有用知识。
本文目录一览:- 如何在SQL Server Management Studio中将1设置为0'-1关系(sql 1=0)
- c# – 在SQL Server Management Studio中创建一个新菜单项
- SQL Server Management Studio中'go'附近的语法不正确
- SQL Server 在Management Studio中使用Web浏览器
- sql-server – SQL Server Management Studio中的“收藏夹”或“宏”?
如何在SQL Server Management Studio中将1设置为0'-1关系(sql 1=0)
我有表:
Users{UserId ...}Professors{UserId ...}
我UserId
在两个表中都设置为PK,并建立了1:1关系。
但是,如果我尝试插入新用户,则无法使用,因为它也需要在Professor
表中插入。
我想使一个用户在Professor表中只能有1条记录,但我也想使其不必在Professor表中存在(我不想让所有用户都教授:))。
如何在SQL Server Management Studio中将1设置为(0 … 1)关系?
我知道将强制执行键约束设置为NO并不是解决方案:)
答案1
如果您有以下要求:
- 用户可以是教授,也可以不是
- 教授永远是用户
那么你是正确的,那是一种1 :: 0..1
关系。在SQL中,可以这样实现:
CREATE TABLE Users ( UserId INT NOT NULL , ... , PRIMARY KEY (UserId) ) ;CREATE TABLE Professors ( UserId INT NOT NULL , ... , PRIMARY KEY (UserId) , FOREIGN KEY (UserId) REFERENCES Users (UserId) ) ;
根据您的描述,您可能已经以相反的顺序定义了外键约束。
c# – 在SQL Server Management Studio中创建一个新菜单项
例如,当您右键单击数据库时,会出现一个选项列表(新数据库,新查询…).
是否可以在该列表中添加新项目并在单击该按钮时实现一些C#功能?
解决方法
在菜单中添加新项
向菜单添加新项目
- On the Tools menu,click Options.
- In the Customize dialog Box,on the Commands tab,click New Menu.
- On the Commands Box,drag New Menu to the menu bar and drop it where you want the new menu to appear.
- On the menu,right-click New Menu,and in the Name Box,type a name for the new menu.
- In the Customize dialog Box,select category such as File,and select a command such as Open File. Drag the command to the new menu. As you point to the new menu,the menu will expand. Drop the command onto the expanded menu.
- In the Customize dialog Box,click Close.
SQL Server Management Studio中'go'附近的语法不正确
如何解决SQL Server Management Studio中''go''附近的语法不正确?
sql Server Management Studio无法处理某些不可打印的字符。
检查换行符,可能您使用的是Linux(LF)或Mac样式(CR),而不是Windows样式(CR和LF)。您可以使用任何高级文本编辑器进行检查,例如Notepad++路
解决方法
执行以下SQL:
drop function f
go
在MS Sql Server Management Studio中,给我这个解析错误:
消息102,级别15,状态1,第1行’go’附近的语法不正确。
为什么?
如果我打开一个新选项卡并将SQL复制/粘贴到其中,它也会失败。但是,如果我打开一个新选项卡并完全重新输入SQL,它就可以正常工作。
SQL Server 在Management Studio中使用Web浏览器
我们在sql Server Management Studio中写sql 的时候,避免不了在浏览器和SSMS两者之间频繁切换,并浪费时间,殊不知,SSMS中自带有一个Web浏览器,和操作查询标签是一样的,非常的方便。
在SSMS中点击“视图”》“其他窗口”》“Web浏览器”,就会打开如下图所示:
这样我们就可以在SSMS中打开web浏览器进行查询信息了,是不是很方便。
上面这个,还是避免不了在浏览器标签和查询标签之间来回切换,如果打开的浏览器标签过多,我们的显示器还有限,就会把我们的查询标签给挤到下面去,就不好找了。有什么办法可以解决呢?
办法是有的,在浏览器标签鼠标“右击”,会出现下图所示:
我们选择“新建垂直选项卡组”,就会把查询标签和浏览器标签分开了,如下图:
这样,在浏览器标签组打开多个标签,并不影响查询标签组,我们就可以一边写sql,一边查信息,是不是更方便了!
sql-server – SQL Server Management Studio中的“收藏夹”或“宏”?
就像现在一样,我必须展开对象资源管理器,折叠/展开两到八棵树,右键单击我的数据库,然后选择“新建查询”.我认为没办法做到这一点,这可能每天节省我30-60秒,这至少值1美元和NINE CENTS.
解决方法
SSMSBoost还允许您定义别名(而不是server8273128> MainServer,server231232> BackupServer等.)
它有更多功能 – 但它们超出了本主题的范围.
查看图片 – 您可以看到快速连接交换机组合框与来自首选连接的一些服务器,“SSMSBoostDemoServer” – 是服务器的别名,下一个名称 – 是原始的.
还有一件事 – 免费版提供加载项.
关于如何在SQL Server Management Studio中将1设置为0'-1关系和sql 1=0的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于c# – 在SQL Server Management Studio中创建一个新菜单项、SQL Server Management Studio中'go'附近的语法不正确、SQL Server 在Management Studio中使用Web浏览器、sql-server – SQL Server Management Studio中的“收藏夹”或“宏”?等相关内容,可以在本站寻找。
此处将为大家介绍关于SQL Server 2016中的Json函数的详细内容,并且为您解答有关sql server json 解析的相关问题,此外,我们还将为您介绍关于java – Sql Server 2016:为SQL Server连接启用TLS 1.2、jMeter ServerAgent在Windows Server 2016中崩溃、jquery – SQL Server中的JSON数据处理、SQL Server 2012 R2升级到SQL Server 2016无法正常启动数据库服务解决方案的有用信息。
本文目录一览:- SQL Server 2016中的Json函数(sql server json 解析)
- java – Sql Server 2016:为SQL Server连接启用TLS 1.2
- jMeter ServerAgent在Windows Server 2016中崩溃
- jquery – SQL Server中的JSON数据处理
- SQL Server 2012 R2升级到SQL Server 2016无法正常启动数据库服务解决方案
SQL Server 2016中的Json函数(sql server json 解析)
这是我的JSON
[{"type": "FormBlock","id": "07bac163-1765-1fee-dba7-6668f8d8507f","x": 50,"y": 57,"width": 120,"height": 50,"alpha": 1,"angle": 0,"userData": {"schema":"{"form":[{"id":"1493828935122"},{"id":"1495115355556"}]}]
我的查询
SELECT JSON_VALUE((SELECT JSON_QUERY([Schema].[schema],''$[0]'') FROM [dbo].[Schema] WHERE objecttype=''test''),''$.userData.schema.form[0].id'')
[Schema]。[schema]:具有列[schema]的表[Schema](包含json)
我可以获取userData.schema数据,但是如果我想拥有userData.schema.form.id,它就不会工作。为什么?
答案1
假设您有以下文档存储在SQL中:
CREATE TABLE JSONTable ( ID int IDENTITY (1,1) PRIMARY KEY CLUSTERED,JSONDocument nvarchar(max) )INSERT INTO JSONTableSELECT ''{ "FilmDetails":{ "ProductNumber":"9912088751", "Title":"Brave", "Type":"Movie", "Runtime":93, "ReleaseYear":2012, "Synopses":[ { "Locale":"en", "Text":"Princess Merida uses her bravery and archery skills to battle a curse and restore peace..." }, { "Locale":"de", "Text":"Animiert" }, { "Locale":"fr", "Text":"Au coeur des contr茅es sauvages d脡cosse, Merida, la fille du roi Fergus et de la reine Elinor..."}], "Assets":[ { "Name":"Stickers", "AssetType":"Stickers", "FileType":"PDF", "Location":"http://media.brave.stickers.pdf", "Locale":"en-US" }, { "Name":"Trailer - WMV", "AssetType":"Trailer - WMV", "FileType":"Video", "Location":"http://youtu.be/Shg79Shgn", "Locale":"en-US" }] } }''
您可以像这样查询数组:
SELECT JSON_VALUE(JSONDocument, ''$.FilmDetails.ProductNumber'') as ProductNumber ,JSON_VALUE(JSONDocument, ''$.FilmDetails.Title'') as Title ,JSON_VALUE(JSONDocument, ''$.FilmDetails.Type'') as ContentType ,JSON_VALUE(JSONDocument, ''$.FilmDetails.Runtime'') as Runtime ,JSON_VALUE(JSONDocument, ''$.FilmDetails.ReleaseYear'') as ReleaseYear ,Locale ,SynopsesText ,Name AS AssetName ,FileType AS AssetFileType ,[Location] AS AssetLocationFROM JSONTableCROSS APPLY OPENJSON(JSONDocument, ''$.FilmDetails.Synopses'')WITH ( Locale varchar(3) ''$.Locale'' ,SynopsesText nvarchar(2000) ''$.Text'') CROSS APPLY OPENJSON(JSONDocument, ''$.FilmDetails.Assets'')WITH ( Name varchar(25) ''$.Name'' ,FileType varchar(25) ''$.FileType'' ,[Location] nvarchar(500) ''$.Location'' ) WHERE JSON_VALUE(JSONDocument, ''$.FilmDetails.Title'') LIKE ''%Brave%'' AND Locale = ''en'' AND FileType = ''video''
这是我不久前写的一篇博客文章,但我认为它可以为您提供所需的内容,可以查询数组。
java – Sql Server 2016:为SQL Server连接启用TLS 1.2
我们有Java 8 Web应用程序,我们强制Web应用程序只使用TLS1.2使用JVM参数-Djdk.tls.client.protocols =“TLSv1.2”(如果我删除此JVM参数应用程序连接到sql server罚款),但我们看到下面的错误虽然为sql服务器启用了TLSv1.2
org.apache.commons.dbcp.sqlnestedException: Cannot create PoolableConnectionFactory (The driver Could not establish a secure connection to sql Server by using Secure Sockets Layer (SSL) encryption. Error: "Server chose TLSv1,but that protocol version is not enabled or not supported by the client.". ClientConnectionId:7564b6a1-60c0-4a24-8baa-7bd21f9512cf)
我们还有一个.Net 2.0 Windows服务(在注册表中只启用了TLSv1.2),它也无法连接到sql Server 2016
System.Data.OleDb.OleDbException: [dbnETLIB][Connectionopen (SECCreateCredentials()).]SSL Security error. at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr,OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionoptions options,Object poolGroupProviderInfo,DbConnectionPool pool,DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection,DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection,DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.open()
但是,如果我在注册表中启用SSL3和TLS1.0,.Net 2.0 Windows服务可以很好地连接到sql Server 2016.
我怀疑,问题是sql Server没有使用TLSv1.2,虽然在sql Server VM上启用了TLSv1.2,如果有更多的配置或补丁需要应用于sql Server以支持TLSv1.2,有人可以帮助我吗?
解决方法
HKey_Local_Machine\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols
通常,此键包含以下子项:
PCT 1.0,SSL 2.0,SSL 3.0,TLS 1.0 …
每个密钥都包含有关密钥协议的信息.可以在服务器上启用这些协议中的任何一个.为此,您需要在协议的服务器子项中创建新的DWORD值.您将DWORD值设置为“1”.
重要说明:在修改注册表之前备份注册表.然后,您可以在出现问题时还原注册表.
要启用TLS 1.x协议,请执行以下步骤:
单击“开始”,单击“运行”,键入regedt32或键入regedit,然后单击“确定”.
在注册表编辑器中,找到以下注册表项:
HKey_Local_Machine\System\CurrentControlSet\Control\SecurityProviders \SCHANNEL\Protocols\TLS 1.x\Server
在“编辑”菜单上,单击“添加值”.
在“数据类型”列表中,单击“DWORD”.
在“值名称”框中,键入“已启用”,然后单击“确定”.
注意如果存在此值,请双击该值以编辑其当前值.
在二进制编辑器中键入11111111,将新键的值设置为“1”.
单击确定.重启电脑.
希望这可以帮助…
jMeter ServerAgent在Windows Server 2016中崩溃
这听起来像是SIGAR bug,但不幸的是您无能为力(除非您想调查sigar-amd64-winnt.dll
的问题,实施解决方案,将其贡献给SIGAR上游并更新JMeter PerfMon固定版本的插件)
同时,您可以考虑将SSHMon Samples Collector作为解决方法,请查看How to Monitor Server Resource Utilization with JMeter’s SSHMon Listener文章以了解更多详细信息
jquery – SQL Server中的JSON数据处理
这是我的json字符串
{ “纬度”: “22.5712854”},{ “经度”: “88.4266847”}
我只想使用TSQL查询来获得纬度和经度.
解决方法
Aslo Ric Vander Ark创造了他自己的功能,但我没有测试它.您可以在文章:A Function to Split JSON Data上阅读更多内容
SQL Server 2012 R2升级到SQL Server 2016无法正常启动数据库服务解决方案
原定周末把公司的TFS升级到2018,由于TFS 2018需要SQL Server至少是2016以上版本,所以还需要将原来的SQL Server 2012 R2一并升级。今天早上负责的同事告诉我升级失败了。SQL Server 2016的数据库服务无法正常启动。他期间还尝试修复了一次SQL Server 2016,仍然提示无法正常启动数据库服务。错误提示如下:
Action required:
Use the following information to resolve the error, and then try the setup process again.
Feature failure reason:
An error occurred during the setup process of the feature.
Error details:
§ Error installing SQL Server Database Engine Services Instance Features
The service did not respond to the start or control request in a timely fashion.
Error code: 0x80004005
Visit http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=13.0.1711.0&EvtType=0xDC112D1C%400xDC80C325&EvtType=0xDC112D1C%400xDC80C325 to get help on troubleshooting.
Warning details:
§ Missing or unspecified settings that were configured to default values:
Service SID support has been enabled on the service.
给予的帮助不是很大,先打开事件查看器找找有什么错误信息:
Windows cannot access the file for one of the following reasons: there is a problem with the network connection, the disk that the file is stored on, or the storage drivers installed on this computer; or the disk is missing. Windows closed the program SQL Server Windows NT - 64 Bit because of this error.
Program: SQL Server Windows NT - 64 Bit
File:
The error value is listed in the Additional Data section.
User Action
1. Open the file again. This situation might be a temporary problem that corrects itself when the program runs again.
2. If the file still cannot be accessed and
- It is on the network, your network administrator should verify that there is not a problem with the network and that the server can be contacted.
- It is on a removable disk, for example, a floppy disk or CD-ROM, verify that the disk is fully inserted into the computer.
3. Check and repair the file system by running CHKDSK. To run CHKDSK, click Start, click Run, type CMD, and then click OK. At the command prompt, type CHKDSK /F, and then press ENTER.
4. If the problem persists, restore the file from a backup copy.
5. Determine whether other files on the same disk can be opened. If not, the disk might be damaged. If it is a hard disk, contact your administrator or computer hardware vendor for further assistance.
Additional Data
Error value: 00000000
Disk type: 0
错误提示我们可以选择运行一下磁盘检查,凭经验觉得还是再看一次SQL Server 2016的安装日志,Summary内容如下:
Overall summary:
Final result: Failed: see details below
Exit code (Decimal): -2068119551
Start time: 2018-07-23 09:27:05
End time: 2018-07-23 09:42:09
Requested action: Repair
Setup completed with required actions for features.
Troubleshooting information for those features:
Next step for SQLEngine: Use the following information to resolve the error, and then try the setup process again.
Next step for FullText: Use the following information to resolve the error, and then try the setup process again.
Next step for AS: Use the following information to resolve the error, and then try the setup process again.
Machine Properties:
Machine name: SQL
Machine processor count: 4
OS version: Microsoft Windows Server 2012 Datacenter (6.2.9200)
OS service pack:
OS region: United States
OS language: English (United States)
OS architecture: x64
Process architecture: 64 Bit
OS clustered: No
Product features discovered:
Product Instance Instance ID Feature Language Edition Version Clustered Configured
SQL Server 2012 MSSQL2 MSSQL11.MSSQL2 Database Engine Services 1033 Enterprise Edition 11.2.5058.0 No Yes
SQL Server 2012 MSSQL2 MSSQL11.MSSQL2 Full-Text and Semantic Extractions for Search 1033 Enterprise Edition 11.2.5058.0 No Yes
SQL Server 2012 SSMS 1033 Enterprise Edition 11.2.5058.0 No Yes
SQL Server 2012 Adv_SSMS 1033 Enterprise Edition 11.2.5058.0 No Yes
SQL Server 2016 MSSQLSERVER MSSQL13.MSSQLSERVER Database Engine Services 1033 Enterprise Edition 13.0.1601.5 No Yes
SQL Server 2016 MSSQLSERVER MSSQL13.MSSQLSERVER Full-Text and Semantic Extractions for Search 1033 Enterprise Edition 13.0.1601.5 No Yes
SQL Server 2016 MSSQLSERVER MSAS13.MSSQLSERVER Analysis Services 1033 Enterprise Edition 13.0.1601.5 No Yes
SQL Server 2016 MSSQLSERVER MSRS13.MSSQLSERVER Reporting Services - Native 1033 Enterprise Edition 13.0.1601.5 No Yes
Package properties:
Description: Microsoft SQL Server 2016
ProductName: SQL Server 2016
Type: RTM
Version: 13
SPLevel: 0
Installation location: I:\x64\setup\
Installation edition: Enterprise
User Input Settings:
ACTION: Repair
AGTDOMAINGROUP: <empty>
AGTSVCACCOUNT: NT Service\SQLSERVERAGENT
AGTSVCPASSWORD: <empty>
AGTSVCSTARTUPTYPE: Manual
ASCONFIGDIR: Config
ASSVCACCOUNT: NT Service\MSSQLServerOLAPService
ASSVCPASSWORD: <empty>
ASTELSVCACCT: NT Service\SSASTELEMETRY
ASTELSVCPASSWORD: <empty>
ASTELSVCSTARTUPTYPE: Automatic
CLTSTARTUPTYPE: 0
CLTSVCACCOUNT: <empty>
CLTSVCPASSWORD: <empty>
CONFIGURATIONFILE: C:\Program Files\Microsoft SQL Server\130\Setup Bootstrap\Log\20180723_092704\ConfigurationFile.ini
CTLRSTARTUPTYPE: 0
CTLRSVCACCOUNT: <empty>
CTLRSVCPASSWORD: <empty>
ENU: true
EXTSVCACCOUNT: <empty>
EXTSVCPASSWORD: <empty>
FAILOVERCLUSTERGROUP: <empty>
FAILOVERCLUSTERNETWORKNAME: <empty>
FTSVCACCOUNT: NT Service\MSSQLFDLauncher
FTSVCPASSWORD: <empty>
HELP: false
IACCEPTROPENLICENSETERMS: false
INDICATEPROGRESS: false
INSTANCENAME: MSSQLSERVER
ISSVCACCOUNT: NT AUTHORITY\Network Service
ISSVCPASSWORD: <empty>
ISSVCSTARTUPTYPE: Automatic
ISTELSVCACCT: <empty>
ISTELSVCPASSWORD: <empty>
ISTELSVCSTARTUPTYPE: 0
MRCACHEDIRECTORY:
QUIET: false
QUIETSIMPLE: false
SQLSVCACCOUNT: NT Service\MSSQLSERVER
SQLSVCPASSWORD: <empty>
SQLTELSVCACCT: NT Service\SQLTELEMETRY
SQLTELSVCPASSWORD: <empty>
SQLTELSVCSTARTUPTYPE: Automatic
SUPPRESSPRIVACYSTATEMENTNOTICE: false
UIMODE: Normal
X86: false
Configuration file: C:\Program Files\Microsoft SQL Server\130\Setup Bootstrap\Log\20180723_092704\ConfigurationFile.ini
Detailed results:
Feature: Database Engine Services
Status: Failed: see logs for details
Reason for failure: An error occurred during the setup process of the feature.
Next Step: Use the following information to resolve the error, and then try the setup process again.
Component name: SQL Server Database Engine Services Instance Features
Component error code: 0x80004005
Error description: The service did not respond to the start or control request in a timely fashion.
Error help link: http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=13.0.1711.0&EvtType=0xDC112D1C%400xDC80C325&EvtType=0xDC112D1C%400xDC80C325
Feature: Full-Text and Semantic Extractions for Search
Status: Failed: see logs for details
Reason for failure: An error occurred for a dependency of the feature causing the setup process for the feature to fail.
Next Step: Use the following information to resolve the error, and then try the setup process again.
Component name: SQL Server Database Engine Services Instance Features
Component error code: 0x80004005
Error description: The service did not respond to the start or control request in a timely fashion.
Error help link: http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=13.0.1711.0&EvtType=0xDC112D1C%400xDC80C325&EvtType=0xDC112D1C%400xDC80C325
Feature: Reporting Services - Native
Status: Passed
Feature: Analysis Services
Status: Failed: see logs for details
Reason for failure: An error occurred during the setup process of the feature.
Next Step: Use the following information to resolve the error, and then try the setup process again.
Component name: SQL Server Analysis Services
Component error code: 0x84BB0001
Error description: The service did not respond to the start or control request in a timely fashion.
Error help link: http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=13.0.1711.0&EvtType=0xDC112D1C%400xDC80C325&EvtType=0xDC112D1C%400xDC80C325
Feature: SQL Browser
Status: Passed
Feature: SQL Writer
Status: Passed
Feature: SQL Client Connectivity
Status: Passed
Feature: SQL Client Connectivity SDK
Status: Passed
Feature: Setup Support Files
Status: Passed
Rules with failures:
Global rules:
There are no scenario-specific rules.
Rules report file: C:\Program Files\Microsoft SQL Server\130\Setup Bootstrap\Log\20180723_092704\SystemConfigurationCheck_Report.htm
The following warnings were encountered while configuring settings on your SQL Server. These resources / settings were missing or invalid so default values were used in recreating the missing resources. Please review to make sure they don’t require further customization for your applications:
Service SID support has been enabled on the service.
大致意思就是数据库服务无法正常启动,更要命的是Error Help Link点击打开后自动回到了微软官网,没有缩小错误范围的价值。于是继续查看Detail.txt,文件内容比较多只把error和exception作为搜索关键字定位,下面只贴出相关信息(期间学习了一下:查看和阅读 SQL Server 安装程序日志文件):
(01) 2018-07-23 09:32:14 Slp: The configuration failure category of current exception is ConfigurationFailure
(01) 2018-07-23 09:32:14 Slp: Configuration action failed for feature SQL_Engine_Core_Inst during timing ConfigRC and scenario ConfigRC.
(01) 2018-07-23 09:32:14 Slp: System.ComponentModel.Win32Exception (0x80004005): The service did not respond to the start or control request in a timely fashion.
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.Sco.Service.StartService(String[] startParams)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlEngine.SqlServerServiceSCM.StartSqlServer(String[] parameters, Boolean withFailpoint)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.UpgradeSQLServerSystemDatabases(EffectiveProperties properties, Boolean isConfiguringTemplateDBs, Boolean fShutdown)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.Upgrade_ConfigRC(Version fromVersion, EffectiveProperties properties, Boolean shutdownRightAway)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.RepairFailedUpgrade(ConfigActionTiming timing, Dictionary`2 actionData)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.Repair(ConfigActionTiming timing, Dictionary`2 actionData, PublicConfigurationBase spcb)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlConfigBase.PrivateConfigurationBase.Execute(ConfigActionScenario scenario, ConfigActionTiming timing, ConfigBaseAction action, Dictionary`2 actionData, PublicConfigurationBase spcbCurrent)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlConfigBase.SqlFeatureConfigBase.Execute(ConfigActionScenario scenario, ConfigActionTiming timing, ConfigBaseAction action, Dictionary`2 actionData, PublicConfigurationBase spcbCurrent)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.ExecuteAction(String actionId)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.Execute(String actionId, TextWriter errorStream)
(01) 2018-07-23 09:32:14 Slp: The following is an exception stack listing the exceptions in outermost to innermost order
(01) 2018-07-23 09:32:14 Slp: Inner exceptions are being indented
(01) 2018-07-23 09:32:14 Slp:
(01) 2018-07-23 09:32:14 Slp: Exception type: System.ComponentModel.Win32Exception
(01) 2018-07-23 09:32:14 Slp: Message:
(01) 2018-07-23 09:32:14 Slp: The service did not respond to the start or control request in a timely fashion.
(01) 2018-07-23 09:32:14 Slp:
(01) 2018-07-23 09:32:14 Slp: HResult : 0x80004005
(01) 2018-07-23 09:32:14 Slp: Error : 1053
(01) 2018-07-23 09:32:14 Slp: Data:
(01) 2018-07-23 09:32:14 Slp: SQL.Setup.FailureCategory = ConfigurationFailure
(01) 2018-07-23 09:32:14 Slp: WatsonConfigActionData = REPAIR@CONFIGRC@SQL_ENGINE_CORE_INST
(01) 2018-07-23 09:32:14 Slp: WatsonExceptionFeatureIdsActionData = System.String[]
(01) 2018-07-23 09:32:14 Slp: Stack:
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.Sco.Service.StartService(String[] startParams)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlEngine.SqlServerServiceSCM.StartSqlServer(String[] parameters, Boolean withFailpoint)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.UpgradeSQLServerSystemDatabases(EffectiveProperties properties, Boolean isConfiguringTemplateDBs, Boolean fShutdown)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.Upgrade_ConfigRC(Version fromVersion, EffectiveProperties properties, Boolean shutdownRightAway)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.RepairFailedUpgrade(ConfigActionTiming timing, Dictionary`2 actionData)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.Repair(ConfigActionTiming timing, Dictionary`2 actionData, PublicConfigurationBase spcb)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlConfigBase.PrivateConfigurationBase.Execute(ConfigActionScenario scenario, ConfigActionTiming timing, ConfigBaseAction action, Dictionary`2 actionData, PublicConfigurationBase spcbCurrent)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlConfigBase.SqlFeatureConfigBase.Execute(ConfigActionScenario scenario, ConfigActionTiming timing, ConfigBaseAction action, Dictionary`2 actionData, PublicConfigurationBase spcbCurrent)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.ExecuteAction(String actionId)
(01) 2018-07-23 09:32:14 Slp: at Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.Execute(String actionId, TextWriter errorStream)
(01) 2018-07-23 09:32:14 Slp: Watson Bucket 1
Original Parameter Values
看了几个错误日志,总之就是围绕启动服务出错。干脆启动SQL Server单机模式碰碰运气。在cmd里输入:
sqlservr.exe -m
运行后,错误提示:"The application was unable to start correctly (0xc0000142)"。还是没有得到进一步的进展,我决定运行Procmon分别抓取正常机器和这台错误机器的执行信息,发现区别就在于错误的机器在读取sqltses.ini后便退出了进程。在这之前werfault相关的操作也进入视野,决定用WinDbg看一下相关的hdmp文件。运行WinDbg并输入:
!analyze -v
*******************************************************************************
* *
* Exception Analysis *
* *
*******************************************************************************
Unable to load image C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Binn\sqldk.dll, Win32 error 0n2
*** WARNING: Unable to verify timestamp for sqldk.dll
GetUrlPageData2 (WinHttp) failed: 12002.
KEY_VALUES_STRING: 1
STACKHASH_ANALYSIS: 1
TIMELINE_ANALYSIS: 1
Timeline: !analyze.Start
Name: <blank>
Time: 2018-07-23T06:27:15.719Z
Diff: 3227719 mSec
Timeline: Dump.Current
Name: <blank>
Time: 2018-07-23T05:33:28.0Z
Diff: 0 mSec
Timeline: Process.Start
Name: <blank>
Time: 2018-07-23T05:33:27.0Z
Diff: 1000 mSec
Timeline: OS.Boot
Name: <blank>
Time: 2018-07-23T02:45:30.0Z
Diff: 10078000 mSec
DUMP_CLASS: 2
DUMP_QUALIFIER: 400
CONTEXT: (.ecxr)
rax=0000000000000000 rbx=00000000000000c4 rcx=00000000ffffffff
rdx=0000000000000000 rsi=000000000000009d rdi=000007faeafbce48
rip=000007fb0bd831f3 rsp=0000001803fef100 rbp=0000000000000000
r8=0000000000000000 r9=0000000000000000 r10=0000000000000000
r11=000007faeb398310 r12=000007faeab52ab0 r13=0000000000000000
r14=000007faeab50000 r15=0000000000000000
iopl=0 nv up ei pl zr na po nc
cs=0033 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00010246
msvcr120!log10+0x313:
000007fb`0bd831f3 c5e173d034 vpsrlq xmm3,xmm0,34h
Resetting default scope
FAULTING_IP:
msvcr120!log10+313 [f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm @ 420]
000007fb`0bd831f3 c5e173d034 vpsrlq xmm3,xmm0,34h
EXCEPTION_RECORD: (.exr -1)
ExceptionAddress: 000007fb0bd831f3 (msvcr120!log10+0x0000000000000313)
ExceptionCode: c000001d (Illegal instruction)
ExceptionFlags: 00000000
NumberParameters: 0
DEFAULT_BUCKET_ID: ILLEGAL_INSTRUCTION
ERROR_CODE: (NTSTATUS) 0xc000001d - {EXCEPTION} Illegal Instruction An attempt was made to execute an illegal instruction.
EXCEPTION_CODE: (NTSTATUS) 0xc000001d - {EXCEPTION} Illegal Instruction An attempt was made to execute an illegal instruction.
EXCEPTION_CODE_STR: c000001d
WATSON_BKT_PROCSTAMP: 5724ae45
WATSON_BKT_PROCVER: 2015.130.1601.5
WATSON_BKT_MODULE: msvcr120.dll
WATSON_BKT_MODSTAMP: 56bc00d3
WATSON_BKT_MODOFFSET: 931f3
WATSON_BKT_MODVER: 12.0.40649.5
MODULE_VER_PRODUCT: Microsoft? Visual Studio? 2013
BUILD_VERSION_STRING: 6.2.9200.16384 (win8_rtm.120725-1247)
MODLIST_WITH_TSCHKSUM_HASH: c6a5860b5b55160212c48b9276e6eba3de41b840
MODLIST_SHA1_HASH: 8ff0cba4b013ab435c80aab51efa92ac767733be
NTGLOBALFLAG: 0
PROCESS_BAM_CURRENT_THROTTLED: 0
PROCESS_BAM_PREVIOUS_THROTTLED: 0
APPLICATION_VERIFIER_FLAGS: 0
PRODUCT_TYPE: 3
SUITE_MASK: 400
DUMP_FLAGS: d96
DUMP_TYPE: 0
PROCESS_NAME: unknown
ANALYSIS_SESSION_HOST: JUNCHU-XPS
ANALYSIS_SESSION_TIME: 07-23-2018 14:27:15.0719
ANALYSIS_VERSION: 10.0.17712.1000 amd64fre
THREAD_ATTRIBUTES:
OS_LOCALE: ENU
BUGCHECK_STR: ILLEGAL_INSTRUCTION
PRIMARY_PROBLEM_CLASS: ILLEGAL_INSTRUCTION
PROBLEM_CLASSES:
ID: [0n321]
Type: [@APPLICATION_FAULT_STRING]
Class: Primary
Scope: DEFAULT_BUCKET_ID (Failure Bucket ID prefix)
BUCKET_ID
Name: Omit
Data: Add
String: [ILLEGAL_INSTRUCTION]
PID: [Unspecified]
TID: [Unspecified]
Frame: [0]
LAST_CONTROL_TRANSFER: from 000007faeabdb342 to 000007fb0bd831f3
STACK_TEXT:
00000018`03fef100 000007fa`eabdb342 : 00000000`000000dd 000007fa`ea7e2679 00003862`7c0b2ebe 000007fb`1906c113 : msvcr120!log10+0x313
00000018`03fef160 000007fb`0bd1276b : 00000000`000000c4 00000000`00000000 00000000`0000009d 000007fb`1905a57e : sqltses!InitializeRoundArrays+0x42
00000018`03fef250 000007fa`eab869d6 : 00000000`00000000 00000018`03fef8d0 00000018`03fef8d0 000007fa`ea698920 : msvcr120!_initterm+0x3f
00000018`03fef280 000007fa`eab52b72 : 00000000`00000001 00000018`03fef670 00000000`00000001 000007fa`eab52ab0 : sqltses!CRT_INIT+0x1df
00000018`03fef2c0 000007fb`1905b9be : 000007fa`eab50000 00000018`03fef8d0 00000000`00000001 00000018`041551e0 : sqltses!DllMainCRTStartup+0xb6
00000018`03fef300 000007fb`1907b3fc : 00000018`04154f10 000007fa`eab50000 00000018`04154e90 00000018`04154df0 : ntdll!LdrpCallInitRoutine+0x3e
00000018`03fef350 000007fb`1907a88b : 00000018`04154f10 00000018`04154f01 00000018`03fef400 000007fb`190c9dd0 : ntdll!LdrpInitializeNode+0x192
00000018`03fef450 000007fb`1907e74e : 00000018`04154400 00000018`04154700 00000018`03fef4d0 000007fb`1906aa52 : ntdll!LdrpInitializeGraph+0x6f
00000018`03fef490 000007fb`1907e74e : 00000000`00000000 00000018`041523b0 00000018`03fef510 00000000`00000003 : ntdll!LdrpInitializeGraph+0x8d
00000018`03fef4d0 000007fb`19082858 : 00000000`00000000 00000000`00000000 00000018`03fef550 00000000`00000001 : ntdll!LdrpInitializeGraph+0x8d
00000018`03fef510 000007fb`19081826 : 00000018`03fef8d0 000007fb`19083ce3 00000000`00000000 000007f7`7d8b8000 : ntdll!LdrpInitializeProcess+0x1a1b
00000018`03fef810 000007fb`1906c1ae : 00000018`03fef8d0 00000000`00000000 000007f7`7d8b8000 00000000`00000000 : ntdll!_LdrpInitialize+0x1565e
00000018`03fef880 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : ntdll!LdrInitializeThunk+0xe
FAILED_INSTRUCTION_ADDRESS:
msvcr120!log10+313 [f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm @ 420]
000007fb`0bd831f3 c5e173d034 vpsrlq xmm3,xmm0,34h
THREAD_SHA1_HASH_MOD_FUNC: 4bb6d88aecf5843ccdb8c6a0528c256becdc603e
THREAD_SHA1_HASH_MOD_FUNC_OFFSET: 1732d2863928a4e53da11554f7406e3cc67c47dd
THREAD_SHA1_HASH_MOD: b5fd421a131c6f1c77c4a87353281934f433e4d5
FOLLOWUP_IP:
msvcr120!log10+313 [f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm @ 420]
000007fb`0bd831f3 c5e173d034 vpsrlq xmm3,xmm0,34h
FAULT_INSTR_CODE: d073e1c5
FAULTING_SOURCE_LINE: f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm
FAULTING_SOURCE_FILE: f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm
FAULTING_SOURCE_LINE_NUMBER: 420
FAULTING_SOURCE_CODE:
No source found for ''f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm''
SYMBOL_STACK_INDEX: 0
SYMBOL_NAME: msvcr120!log10+313
FOLLOWUP_NAME: MachineOwner
MODULE_NAME: msvcr120
IMAGE_NAME: msvcr120.dll
DEBUG_FLR_IMAGE_TIMESTAMP: 56bc00d3
STACK_COMMAND: dt ntdll!LdrpLastDllInitializer BaseDllName ; dt ntdll!LdrpFailureData ; ~0s ; .ecxr ; kb
FAILURE_BUCKET_ID: ILLEGAL_INSTRUCTION_c000001d_msvcr120.dll!log10
BUCKET_ID: ILLEGAL_INSTRUCTION_BAD_IP_msvcr120!log10+313
FAILURE_EXCEPTION_CODE: c000001d
FAILURE_IMAGE_NAME: msvcr120.dll
BUCKET_ID_IMAGE_STR: msvcr120.dll
FAILURE_MODULE_NAME: msvcr120
BUCKET_ID_MODULE_STR: msvcr120
FAILURE_FUNCTION_NAME: log10
BUCKET_ID_FUNCTION_STR: log10
BUCKET_ID_OFFSET: 313
BUCKET_ID_MODTIMEDATESTAMP: 56bc00d3
BUCKET_ID_MODCHECKSUM: f6c2b
BUCKET_ID_MODVER_STR: 12.0.40649.5
BUCKET_ID_PREFIX_STR: ILLEGAL_INSTRUCTION_BAD_IP_
FAILURE_PROBLEM_CLASS: ILLEGAL_INSTRUCTION
FAILURE_SYMBOL_NAME: msvcr120.dll!log10
WATSON_STAGEONE_URL: http://watson.microsoft.com/StageOne/unknown/2015.130.1601.5/5724ae45/msvcr120.dll/12.0.40649.5/56bc00d3/c000001d/000931f3.htm?Retriage=1
TARGET_TIME: 2018-07-23T05:33:28.000Z
OSBUILD: 9200
OSSERVICEPACK: 16384
SERVICEPACK_NUMBER: 0
OS_REVISION: 0
OSPLATFORM_TYPE: x64
OSNAME: Windows 8
OSEDITION: Windows 8 Server TerminalServer DataCenter SingleUserTS
USER_LCID: 0
OSBUILD_TIMESTAMP: 2012-07-26 10:15:22
BUILDDATESTAMP_STR: 120725-1247
BUILDLAB_STR: win8_rtm
BUILDOSVER_STR: 6.2.9200.16384
ANALYSIS_SESSION_ELAPSED_TIME: 591b
ANALYSIS_SOURCE: UM
FAILURE_ID_HASH_STRING: um:illegal_instruction_c000001d_msvcr120.dll!log10
FAILURE_ID_HASH: {5866d3bb-feda-328f-6d8f-83f8512752ce}
Followup: MachineOwner
---------
初步看了一下是调用msvcr120!log10出现了错误并提示“illegal instruction”,原来是VC 2013的错误,log10应该是数学库提供的函数。于是打开必应输入关键字"vc2013 log10 Illegal Instruction",果然是VC 2013的bug,下载对应更新包安装重启计算机问题解决。
官方地址:FIX: Programs that are built in Visual C++ 2013 crash with "Illegal Instruction" exception
关于SQL Server 2016中的Json函数和sql server json 解析的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于java – Sql Server 2016:为SQL Server连接启用TLS 1.2、jMeter ServerAgent在Windows Server 2016中崩溃、jquery – SQL Server中的JSON数据处理、SQL Server 2012 R2升级到SQL Server 2016无法正常启动数据库服务解决方案等相关知识的信息别忘了在本站进行查找喔。
对于如何通过ODBC连接在c#中传递Informix集合参数感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍LIST,SET,MULTISET,并为您提供关于$.ajax () 方法详解 ajax 之 async 属性 【原创】详细案例解剖 —— 浅谈 Redis 缓存的常用 5 种方式(String,Hash,List,set,SetSorted )、Android List,Set,Map集合安全 集合区别 并发集合类性能分析、C++ multiset,STL multiset详解、C++/STL关联容器-集合-multiset&set的用法的有用信息。
本文目录一览:- 如何通过ODBC连接在c#中传递Informix集合参数(LIST,SET,MULTISET)
- $.ajax () 方法详解 ajax 之 async 属性 【原创】详细案例解剖 —— 浅谈 Redis 缓存的常用 5 种方式(String,Hash,List,set,SetSorted )
- Android List,Set,Map集合安全 集合区别 并发集合类性能分析
- C++ multiset,STL multiset详解
- C++/STL关联容器-集合-multiset&set的用法
如何通过ODBC连接在c#中传递Informix集合参数(LIST,SET,MULTISET)
我正在寻找一种在C#中传递Informix列表参数的方法。
我问过一个关于如何将多值参数传递给Informix的问题,但是现在我需要从C#中执行它。
在简历中,我有一个这样的程序。
CREATE PROCEDURE test_3(c LIST(CHAR(10) NOT NULL)) RETURNING CHAR(10) AS r; DEFINE r CHAR(10); FOREACH SELECT * INTO r FROM TABLE(c) RETURN r WITH RESUME; END FOREACH;END PROCEDURE;
像这样在Aqua Data Studio.8.0.22中执行它可以正常工作
EXECUTE PROCEDURE test_3(''LIST{''''stspols'''',''''stsrepo''''}'');
因此,我举了一个简短的示例说明如何在c#中执行它。
首先像 CommandType.Text
string strParameters = "LIST{''''stspols'''',''''stsrepo''''}";using (OdbcConnection oConnection = new OdbcConnection("DSN=MYDSN;UID=MYUID;PWD=MYPWD;")) { oConnection.Open(); using (OdbcDataAdapter oCommand = new OdbcDataAdapter(string.Format("EXECUTE PROCEDURE test_3(''{0}'')", strParameters), oConnection)) { using (DataTable dt = new DataTable()) { oCommand.Fill(dt); } } }
这个作品很好。
所以我很好奇并试图执行它,但是 CommandType.StoredProcedure
string strParameters = "LIST{''''stspols'''',''''stsrepo''''}"; using (OdbcConnection oConnection = new OdbcConnection("DSN=MYDSN;UID=MYUID;PWD=MYPWD;")) { oConnection.Open(); using (OdbcCommand oCommand = new OdbcCommand("{CALL test_3(?)}", oConnection)) { oCommand.CommandType = CommandType.StoredProcedure; OdbcParameter oParameter = new OdbcParameter("c", OdbcType.Char, 4000); oParameter.Value = strParameters; oCommand.Parameters.Add(oParameter); using (OdbcDataAdapter oDataAdapter = new OdbcDataAdapter(oCommand)) { using (DataTable dt = new DataTable()) { oDataAdapter.Fill(dt); } } } }
但是现在我明白了 ERROR [HY000] [Informix][Informix ODBC Driver][Informix]Invalidcollection literal value.
所以所有这些之后,我的最后一个问题是
我如何从C#中使用Collection参数类型(LIST,SET,MULTISET)作为存储过程来执行这种Informix过程。
显然我做错了。
在此先感谢您的宝贵帮助。
答案1
在原始SQL中,加倍的单引号是必需的,但在参数化查询中则不需要。您应该能够替换:
string strParameters = "LIST{''''stspols'''',''''stsrepo''''}";
和:
string strParameters = "LIST{''stspols'',''stsrepo''}";
了解何时需要将引号加倍,何时不应该加倍,但“不在占位符值中”是准确的。
$.ajax () 方法详解 ajax 之 async 属性 【原创】详细案例解剖 —— 浅谈 Redis 缓存的常用 5 种方式(String,Hash,List,set,SetSorted )
$.ajax () 方法详解
jquery 中的 ajax 方法参数总是记不住,这里记录一下。
1.url:
要求为 String 类型的参数,(默认为当前页地址)发送请求的地址。
2.type:
要求为 String 类型的参数,请求方式(post 或 get)默认为 get。注意其他 http 请求方法,例如 put 和 delete 也可以使用,但仅部分浏览器支持。
3.timeout:
要求为 Number 类型的参数,设置请求超时时间(毫秒)。此设置将覆盖 $.ajaxSetup () 方法的全局设置。
4.async:
要求为 Boolean 类型的参数,默认设置为 true,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其他操作必须等待请求完成才可以执行。
5.cache:
要求为 Boolean 类型的参数,默认为 true(当 dataType 为 script 时,默认为 false),设置为 false 将不会从浏览器缓存中加载请求信息。
6.data:
要求为 Object 或 String 类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式。get 请求中将附加在 url 后。防止这种自动转换,可以查看 processData 选项。对象必须为 key/value 格式,例如 {foo1:"bar1",foo2:"bar2"} 转换为 & foo1=bar1&foo2=bar2。如果是数组,JQuery 将自动为不同值对应同一个名称。例如 {foo:["bar1","bar2"]} 转换为 & foo=bar1&foo=bar2。
7.dataType:
要求为 String 类型的参数,预期服务器返回的数据类型。如果不指定,JQuery 将自动根据 http 包 mime 信息返回 responseXML 或 responseText,并作为回调函数参数传递。可用的类型如下:
xml:返回 XML 文档,可用 JQuery 处理。
html:返回纯文本 HTML 信息;包含的 script 标签会在插入 DOM 时执行。
script:返回纯文本 JavaScript 代码。不会自动缓存结果。除非设置了 cache 参数。注意在远程请求时(不在同一个域下),所有 post 请求都将转为 get 请求。
json:返回 JSON 数据。
jsonp:JSONP 格式。使用 SONP 形式调用函数时,例如 myurl?callback=?,JQuery 将自动替换后一个 “?” 为正确的函数名,以执行回调函数。
text:返回纯文本字符串。
8.beforeSend:
要求为 Function 类型的参数,发送请求前可以修改 XMLHttpRequest 对象的函数,例如添加自定义 HTTP 头。在 beforeSend 中如果返回 false 可以取消本次 ajax 请求。XMLHttpRequest 对象是惟一的参数。
function(XMLHttpRequest){
this; // 调用本次 ajax 请求时传递的 options 参数
}
9.complete:
要求为 Function 类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。参数:XMLHttpRequest 对象和一个描述成功请求类型的字符串。
function(XMLHttpRequest, textStatus){
this; // 调用本次 ajax 请求时传递的 options 参数
}
10.success:要求为 Function 类型的参数,请求成功后调用的回调函数,有两个参数。
(1) 由服务器返回,并根据 dataType 参数进行处理后的数据。
(2) 描述状态的字符串。
function(data, textStatus){
//data 可能是 xmlDoc、jsonObj、html、text 等等
this; // 调用本次 ajax 请求时传递的 options 参数
}
11.error:
要求为 Function 类型的参数,请求失败时被调用的函数。该函数有 3 个参数,即 XMLHttpRequest 对象、错误信息、捕获的错误对象 (可选)。ajax 事件函数如下:
function(XMLHttpRequest, textStatus, errorThrown){
// 通常情况下 textStatus 和 errorThrown 只有其中一个包含信息
this; // 调用本次 ajax 请求时传递的 options 参数
}
12.contentType:
要求为 String 类型的参数,当发送信息至服务器时,内容编码类型默认为 "application/x-www-form-urlencoded"。该默认值适合大多数应用场合。
13.dataFilter:
要求为 Function 类型的参数,给 Ajax 返回的原始数据进行预处理的函数。提供 data 和 type 两个参数。data 是 Ajax 返回的原始数据,type 是调用 jQuery.ajax 时提供的 dataType 参数。函数返回的值将由 jQuery 进一步处理。
function(data, type){
// 返回处理后的数据
return data;
}
14.dataFilter:
要求为 Function 类型的参数,给 Ajax 返回的原始数据进行预处理的函数。提供 data 和 type 两个参数。data 是 Ajax 返回的原始数据,type 是调用 jQuery.ajax 时提供的 dataType 参数。函数返回的值将由 jQuery 进一步处理。
function(data, type){
// 返回处理后的数据
return data;
}
15.global:
要求为 Boolean 类型的参数,默认为 true。表示是否触发全局 ajax 事件。设置为 false 将不会触发全局 ajax 事件,ajaxStart 或 ajaxStop 可用于控制各种 ajax 事件。
16.ifModified:
要求为 Boolean 类型的参数,默认为 false。仅在服务器数据改变时获取新数据。服务器数据改变判断的依据是 Last-Modified 头信息。默认值是 false,即忽略头信息。
17.jsonp:
要求为 String 类型的参数,在一个 jsonp 请求中重写回调函数的名字。该值用来替代在 "callback=?" 这种 GET 或 POST 请求中 URL 参数里的 "callback" 部分,例如 {jsonp:''onJsonPLoad''} 会导致将 "onJsonPLoad=?" 传给服务器。
18.username:
要求为 String 类型的参数,用于响应 HTTP 访问认证请求的用户名。
19.password:
要求为 String 类型的参数,用于响应 HTTP 访问认证请求的密码。
20.processData:
要求为 Boolean 类型的参数,默认为 true。默认情况下,发送的数据将被转换为对象(从技术角度来讲并非字符串)以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或者其他不希望转换的信息,请设置为 false。
21.scriptCharset:
要求为 String 类型的参数,只有当请求时 dataType 为 "jsonp" 或者 "script",并且 type 是 GET 时才会用于强制修改字符集 (charset)。通常在本地和远程的内容编码不同时使用。
案例代码:

$(function(){
$(''#send'').click(function(){
$.ajax({
type: "GET",
url: "test.json",
data: {username:$("#username").val(), content:$("#content").val()},
dataType: "json",
success: function(data){
$(''#resText'').empty(); //清空resText里面的所有内容
var html = '''';
$.each(data, function(commentIndex, comment){
html += ''<div><h6>'' + comment[''username'']
+ '':</h6><p'' + comment[''content'']
+ ''</p></div>'';
});
$(''#resText'').html(html);
}
});
});
});

22. 顺便说一下 $.each () 函数:
$.each () 函数不同于 JQuery 对象的 each () 方法,它是一个全局函数,不操作 JQuery 对象,而是以一个数组或者对象作为第 1 个参数,以一个回调函数作为第 2 个参数。回调函数拥有两个参数:第 1 个为对象的成员或数组的索引,第 2 个为对应变量或内容。
ajax 之 async 属性
Ajax 请求中的 async:false/true 的作用
官方的解释是:http://api.jquery.com/jQuery.ajax/
async Boolean Default: true
By default, all requests are sent asynchronous (e.g. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
async. 默认是 true,即为异步方式,$.Ajax 执行后,会继续执行 ajax 后面的脚本,直到服务器端返回数据后,触发 $.Ajax 里的 success 方法,这时候执行的是两个线程。若要将其设置为 false,则所有的请求均为同步请求,在没有返回值之前,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
下面查看一个示例:

1 var temp;
2 $.ajax({
3
4 async: false,
5 type : "POST",
6 url : defaultPostData.url,
7 dataType : ''json'',
8 success : function(data)
9 {
10
11 temp=data;
12 }
13
14 });
15
16 alert(temp);

这个 ajax 请求为同步请求,在没有返回值之前,alert (temp) 是不会执行的。
如果 async 设置为:true,则不会等待 ajax 请求返回的结果,会直接执行 ajax 后面的语句。
不过上面设置同步请求的方法,有网友曾经反馈将 async 设成 false 后,原意是想返回数据了再执行 $.Ajax 后面的脚本,没想到这个地方却导致了在火狐浏览器下出现闪屏 (Firefox 11.0),滚动条下拉到底部触发 ajax 的情况。最后只能将 async:false 注释掉, 也就是 async 为 ture 的情况下,成功解决了火狐浏览器滚动条下拉到底部触发 ajax 出现闪屏的问题。
【原创】详细案例解剖 —— 浅谈 Redis 缓存的常用 5 种方式(String,Hash,List,set,SetSorted )
很多小伙伴没接触过 Redis,以至于去学习的时候感觉云里雾里的,就有一种:教程随你出,懂了算我输的感觉。
每次听圈内人在谈论的时候总是插不上话,小编就偷偷去了解了一下,也算是初入门径。
然后就整理了一下,很简单的一个 demo(小编用的是 C# 语法进行 demo 编写),我们一起来解剖一下。
总共分为两步:
1、安装 Redis 服务器(其实就是一个 CMD 黑窗窗)。
2、编写代码(引入动态链接库、编写 5 种常用存储数据类型)
1、安装 Redis 服务器(Windows 系统)
1)、我们先去微软官网下载一个 Redis GitHub:https://github.com/MSOpenTech/redis/releases,然后选择你喜欢的版本 zip 或 msi 下载。
小编下载了一个放在百度云:https://pan.baidu.com/s/1M7ztZvOmR0YPehbRujkM6Q,提取码:uqmw
下载好了后在 C 盘建立一个 redis 文件夹,解压到 redis。
相关程序说明:
redis.windows.conf 是 redis 的配置文件。
redis-server.exe 服务器端。
redis-cli 命令行客户端。
redis-benchmark:Redis 性能测试工具,测试 Redis 在你的系统及你的配置下的读写性能。
2)、启动服务
Windows+R 输入 cmd 运行,进入我们解压文件的目录(按回车):
cd C:\redis\Redis-x64-3.0.504
进入 redis 目录后,在命令行输入如下命令后回车:
redis-server redis.windows.conf
也可以该命令保存为文件 startup.bat,保存在根目录下,下次就可以直接运行 startup.bat 启动,
到这里我们服务器就安装完成了,接下来我们进行测试,看是否能用(是否安装成功)
3)、测试
另外开启一个命令行窗口 进入 redis 目录下 (注意修改自己的 ip(通过 ipconfig 来查看自己本地的 ip 地址)),第一个命令窗口不要关。
cd C:\redis\Redis-x64-3.0.504
运行如下命令:后面添加 --raw,在输出中文时可避免出现乱码,Ip 是你自己本地的 ip
redis-cli.exe -h 192.168.0.43 -p 6379 --raw
写入 redis 缓存,输入如下代码回车,注意写入的值这里不能有空格,也就是或 HelloWorld 是一个字符串。
set keyStr HelloWorld
读入 redis 缓存,输入如下代码回车
get keyStr
到这里我们 redis 服务器就安装好了,接下来我们写代码测试(记住,命令窗口(黑窗窗)不能关闭,一旦关闭 redis 就关闭了)
2、编写代码(我们使用 C# 语法进行编写)
我先新建一个控制台应用程序:RedisApplication
然后引入三个动态链接库到项目里面,百度网盘下载链接如下:https://pan.baidu.com/s/1xySWqoootlF9la0NJQSVYg,提取码:qlyx
新建一个学生类:Student

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedisApplication
{
public class Student
{
public string id { get; set; }
public string name { get; set; }
}
}

在 Program.cs 编写 redis 缓存与读取,五种方法均在里面,运行时注意吧不测试的注释掉

using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace RedisApplication
{
class Program
{
static void Main(string[] args)
{
//在Redis中存储常用的5种数据类型:string,Hash,List,SetSorted ,set
/// string
/// Hash
/// List
/// SetSorted
/// set
RedisClient client = new RedisClient("192.168.0.43", 6379); //链接Redis服务器
client.FlushAll(); //命令用于清空整个Redis服务器的数据(删除所有数据库的所有密钥)。
#region string
client.Add<string>("StringValueTime", "我已设置过期时间噢30秒后会消失", DateTime.Now.AddMilliseconds(30000));
while (true)
{
if (client.ContainsKey("StringValueTime"))
{
Console.WriteLine("String.键:StringValue,值:{0} {1}", client.Get<string>("StringValueTime"), DateTime.Now);
Thread.Sleep(10000);
}
else
{
Console.WriteLine("键:StringValue,值:我已过期 {0}", DateTime.Now);
break;
}
}
client.Add<string>("StringValue", " String和Memcached操作方法差不多");
Console.WriteLine("数据类型为:String.键:StringValue,值:{0}", client.Get<string>("StringValue"));
Student stud = new Student() { id = "1001", name = "李四" };
client.Add<Student>("StringEntity", stud);
Student Get_stud = client.Get<Student>("StringEntity");
Console.WriteLine("数据类型为:String.键:StringEntity,值:{0} {1}", Get_stud.id, Get_stud.name);
#endregion
#region Hash
client.SetEntryInHash("HashID", "Name", "张三");
client.SetEntryInHash("HashID", "Age", "24");
client.SetEntryInHash("HashID", "Sex", "男");
client.SetEntryInHash("HashID", "Address", "上海市XX号XX室");
List<string> HaskKey = client.GetHashKeys("HashID");
foreach (string key in HaskKey)
{
Console.WriteLine("HashID--Key:{0}", key);
}
List<string> HaskValue = client.GetHashValues("HashID");
foreach (string value in HaskValue)
{
Console.WriteLine("HashID--Value:{0}", value);
}
List<string> AllKey = client.GetAllKeys(); //获取所有的key。
foreach (string Key in AllKey)
{
Console.WriteLine("AllKey--Key:{0}", Key);
}
#endregion
#region List
/*
* list是一个链表结构,主要功能是push,pop,获取一个范围的所有的值等,操作中key理解为链表名字。
* Redis的list类型其实就是一个每个子元素都是string类型的双向链表。我们可以通过push,pop操作从链表的头部或者尾部添加删除元素,
* 这样list既可以作为栈,又可以作为队列。Redis list的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销,
* Redis内部的很多实现,包括发送缓冲队列等也都是用的这个数据结构
*/
client.EnqueueItemOnList("QueueListId", "1.张三"); //入队
client.EnqueueItemOnList("QueueListId", "2.张四");
client.EnqueueItemOnList("QueueListId", "3.王五");
client.EnqueueItemOnList("QueueListId", "4.王麻子");
int q = client.GetListCount("QueueListId");
for (int i = 0; i < q; i++)
{
Console.WriteLine("QueueListId出队值:{0}", client.DequeueItemFromList("QueueListId")); //出队(队列先进先出)
}
client.PushItemToList("StackListId", "1.张三"); //入栈
client.PushItemToList("StackListId", "2.张四");
client.PushItemToList("StackListId", "3.王五");
client.PushItemToList("StackListId", "4.王麻子");
int p = client.GetListCount("StackListId");
for (int i = 0; i < p; i++)
{
Console.WriteLine("StackListId出栈值:{0}", client.PopItemFromList("StackListId")); //出栈(栈先进后出)
}
#endregion
#region Set无序集合
/*
它是string类型的无序集合。set是通过hash table实现的,添加,删除和查找,对集合我们可以取并集,交集,差集
*/
client.AddItemToSet("Set1001", "小A");
client.AddItemToSet("Set1001", "小B");
client.AddItemToSet("Set1001", "小C");
client.AddItemToSet("Set1001", "小D");
HashSet<string> hastsetA = client.GetAllItemsFromSet("Set1001");
foreach (string item in hastsetA)
{
Console.WriteLine("Set无序集合ValueA:{0}", item); //出来的结果是无须的
}
client.AddItemToSet("Set1002", "小K");
client.AddItemToSet("Set1002", "小C");
client.AddItemToSet("Set1002", "小A");
client.AddItemToSet("Set1002", "小J");
HashSet<string> hastsetB = client.GetAllItemsFromSet("Set1002");
foreach (string item in hastsetB)
{
Console.WriteLine("Set无序集合ValueB:{0}", item); //出来的结果是无须的
}
HashSet<string> hashUnion = client.GetUnionFromSets(new string[] { "Set1001", "Set1002" });
foreach (string item in hashUnion)
{
Console.WriteLine("求Set1001和Set1002的并集:{0}", item); //并集
}
HashSet<string> hashG = client.GetIntersectFromSets(new string[] { "Set1001", "Set1002" });
foreach (string item in hashG)
{
Console.WriteLine("求Set1001和Set1002的交集:{0}", item); //交集
}
HashSet<string> hashD = client.GetDifferencesFromSet("Set1001", new string[] { "Set1002" }); //[返回存在于第一个集合,但是不存在于其他集合的数据。差集]
foreach (string item in hashD)
{
Console.WriteLine("求Set1001和Set1002的差集:{0}", item); //差集
}
#endregion
#region SetSorted 有序集合
/*
sorted set 是set的一个升级版本,它在set的基础上增加了一个顺序的属性,这一属性在添加修改.元素的时候可以指定,
* 每次指定后,zset(表示有序集合)会自动重新按新的值调整顺序。可以理解为有列的表,一列存 value,一列存顺序。操作中key理解为zset的名字.
*/
client.AddItemToSortedSet("SetSorted1001", "1.刘仔");
client.AddItemToSortedSet("SetSorted1001", "2.星仔");
client.AddItemToSortedSet("SetSorted1001", "3.猪仔");
List<string> listSetSorted = client.GetAllItemsFromSortedSet("SetSorted1001");
foreach (string item in listSetSorted)
{
Console.WriteLine("SetSorted有序集合{0}", item);
}
#endregion
}
}
}

如下五种方法:
我们运行 Hash 这个方法读取缓存的数据:
很显然,读取成功。
到这里我们的简单 redis 缓存就完成了,是不是很简单,只有理清楚逻辑,一切都好办。
然后小编设想一下,如果我们需要缓存文件,如视频、图片,我们是不是可以先转换为二进制流就行存储读取呢。
这个问题就交给你辣,加油,你可以的。
Android List,Set,Map集合安全 集合区别 并发集合类性能分析
对于Android开发者来说深入了解Java的集合类很有必要主要是从Collection和Map接口衍生出来的,目前主要提供了List、Set和 Map这三大类的集合
Collection接口主要有两种子类分别为List和Set,区别主要是List保存的对象可以重复
而Set不可以重复
而Map一般为key-value这样的对应关系,比如我们常用的HashMap。
数组
数组存储区间是连续的,占用内存严重,故空间复杂的很大。但数组的二分查找时间复杂度小,为O(1);数组的特点是:寻址容易,插入和删除困难;
链表
链表存储区间离散,占用内存比较宽松,故空间复杂度很小,但时间复杂度很大,达O(N)。链表的特点是:寻址困难,插入和删除容易。
哈希表
那么我们能不能综合两者的特性,做出一种寻址容易,插入删除也容易的数据结构?答案是肯定的,这就是我们要提起的哈希表。哈希表((Hash table)既满足了数据的查找方便,同时不占用太多的内容空间,使用也十分方便。
Collection 接口的接口 对象的集合
├ List 子接口 按进入先后有序保存 可重复
│├ LinkedList 接口实现类 链表 插入删除 没有同步 线程不安全
│├ ArrayList 接口实现类 数组 随机访问 没有同步 线程不安全
│└ Vector 接口实现类 数组 同步 线程安全
│ └ Stack
└ Set 子接口 仅接收一次,并做内部排序
├ HashSet
│ └ LinkedHashSet
└ TreeSet
有关这些子类的性能,Android开发网从插入、删除、移动等方面按照元素的执行效率做一一分析,通过分析Sun 的Java源码和实际元素操作得出下面结论:
ArrayList -是线程不安全 底层是由数组实现 他的构造主要从AbstractList实现,主要是判断下初始元素的容量,ArrayList最大的特点就是提供了Add、Get操作,当然可以通过迭代器来遍历,对于元素的存在可以通过contains方法判断。
LinkedList - 线程不安全的 作为一种双向链表结构,对于元素的插入、删除效率比较高,只需要调整节点指向即可,但是对于随机查找而言性能主要看这个链表长度和运气了。 LinkedList也提供了ArrayList的get方法,但是要复杂的多,主要通过next或previous方法遍历得到,LinkedList要移动指针。
Vector -线程安全的,这两个类底层都是由数组实现的,效率低 比较简单和ArrayList差不多,主要是内部实现了synchronized关键字,实现了线程安全访问但性能有些降低,同时对于元素的扩充在算法上和ArrayList稍有不同,通过构造的容量增量系数来决定。
Stack - 作为栈的操作,本次继承于Vector,提供了push,pop和peek方法,peek是不弹出根据数据大小获取最后一个元素对象。
HashSet - 该类是从Set接口继承而来,相对于List而言就是说内部添加的元素不能重复, Hashtable 继承 Map 接口,实现一个 key-value 映射的哈希表。任何非空( non-null )的对象都可作为 key 或者 value 。 当然从名字的Hash来看就是通过哈希算法来实现防止冲突来获得防止重复的,整体上从HashMap实现,存放元素方法的也是类似key- value的对应的,通过迭代器遍历,不过HashSet不是线程安全的。
TreeSet - 这个相对于HashSet而言主要是提供了排序支持,TreeSet是从TreeMap类实现,也是非线程安全的。
可以看到Set的两个类都和Map有关,下面就一起看下有关映射(Map)相关的使用。
HashMap和Hashtable的区别
HashMap和Hashtable都实现了Map接口,但决定用哪一个之前先要弄清楚它们之间的分别。主要的区别有:线程安全性,同步(synchronization),以及速度。
- HashMap几乎可以等价于Hashtable,除了HashMap是非synchronized的,并可以接受null(HashMap可以接受为null的键值(key)和值(value),而Hashtable则不行)。
- HashMap是非synchronized,而Hashtable是synchronized,这意味着Hashtable是线程安全的,多个线程可以共享一个Hashtable;而如果没有正确的同步的话,多个线程是不能共享HashMap的。Java 5提供了ConcurrentHashMap,它是HashTable的替代,比HashTable的扩展性更好。
- 另一个区别是HashMap的迭代器(Iterator)是fail-fast迭代器,而Hashtable的enumerator迭代器不是fail-fast的。所以当有其它线程改变了HashMap的结构(增加或者移除元素),将会抛出ConcurrentModificationException,但迭代器本身的remove()方法移除元素则不会抛出ConcurrentModificationException异常。但这并不是一个一定发生的行为,要看JVM。这条同样也是Enumeration和Iterator的区别。
- 由于Hashtable是线程安全的也是synchronized,所以在单线程环境下它比HashMap要慢。如果你不需要同步,只需要单一线程,那么使用HashMap性能要好过Hashtable。
- HashMap不能保证随着时间的推移Map中的元素次序是不变的。
HashMap - ,可以为空,提供了比较强大的功能实现,比如说loadFactor可以控制元素增长时内存分配,HashMap也是非线程安全的。
C++ multiset,STL multiset详解
multiset 是关联容器的一种,是排序好的集合(元素已经进行了排序),并且允许有相同的元素。不能直接修改 multiset 容器中元素的值。因为元素被修改后,容器并不会自动重新调整顺序,于是容器的有序性就会被破坏,再在其上进行查找等操作就会得到错误的结果。因此,如果要修改 multiset 容器中某个元素的值,正确的做法是先删除该元素,再插入新元素。
使用 multiset 必须包含头文件 <set>。multiset 类模板的定义如下:
template <class Key,class Pred = less<Key>,class B = allocator<Key> > class multiset {
...
};
第一个类型参数说明 multiset 容器中的每个元素都是 Key 类型的。第二个类型参数 Pred 用于指明容器中元素的排序规则,在被实例化后,Pred 可以是函数对象类,也可以是函数指针类型。
multiset 内部在排序时定义了一个变量
Pred op
,根据表达式op(x,y)
来比较两个元素 x、y 的大小。该表达式的值为 true,则说明 x 比 y 小。Pred 的默认值是 less<Key>,less 是 STL 中的函数对象类模板,其定义如下:
template <class_Tp> struct less { bool operator() (const _Tp &__x,const _Tp &__y) const { return __x < __y; } };这说明,在默认情况下,multiset 容器中的元素是用
<
运算符比较大小的。例如,假设 A 是一个类的名字,可以定义一个如下的容器对象:
multiset <A> s;
由于 multiset 的类型参数可以使用默认值,因此上面的语句等价于:multiset < int,less<A>,allocator<A> > s;
模板类 multiset < A,allocator<A> > 的 insert 成员函数可以用来插入一个元素。 插入过程中需要进行元素之间的比较,可以认为 insert 成员函数中定义了一个变量 less <A> op,用 op(x,y) 来比较元素 x、y 的大小。归根到底,还是用<
运算符比较 x、y 的大小。 因此,<
运算符必须经过适当重载,才可以向 multiset <A>容器中插人元素。下面的程序 会编译出错:
#include <set> using namespace std; class A{}; int main(){ multiset <A> a; a.insert( A() ); //编译出错,因为不能用“<”运算符比较两个A对象 }multiset 常用的成员函数如表 1 所示。有的成员函数有不止一个版本,这里不一一 列出。
成员函数或成员函数模板 | 作 用 |
---|---|
iterator find (const T & val); | 在容器中查找值为 val 的元素,返回其迭代器。如果找不到,返 回 end() |
iterator insert( const T & val); | 将 val 插入容器中并返回其迭代器 |
void insert(iterator first,iterator last); | 将区间 [first,last) 中的元素插人容器 |
int count( const T & val); | 统计有多少个元素的值和 val 相等 |
iterator lower_bound( const T & val); | 查找一个最大的位置 it,使得 [begin(), it) 中所有的元素者比 val 小 |
iterator upper_bound( const T & val); | 查找一个最小的位置 it,使得 [it, end()) 中所有的元素都比 val 大 |
pair <iterator,iterator > equal_range (const T & val); | 同时求得 lower_bound 和 upper_bound |
iterator erase(iterator it); | 删除 it 指向的元素,返回其后面的元素的迭代器(Visual Studio 2010 中如此,但是在 C++ 标准和 Dev C++ 中,返回值不是这样) |
iterator erase(iterator first,iterator last); | 删除区间 [first,last),返回 last(Visual Studio 2010 中如此,但是在 C++ 标准和 Dev C++ 中,返回值不是这样) |
multiset 及 set 中的 find 和 count 并不是用
==
运算符比较元素是否和待查找的值相等的。它们进行比较的原则是:如果x比y小
和y比x小
同时为假,就认为 x 和 y 相等。下面通过一个例子说明 multiset 的用法。
#include <iostream> #include <set> //使用multiset须包含此头文件 using namespace std; template <class T> void Print(T first,T last) { for (; first != last; ++first) cout << *first << " "; cout << endl; } class A { private: int n; public: A(int n_) { n = n_; } friend bool operator < (const A & a1,const A & a2) { return a1.n < a2.n; } friend ostream & operator << (ostream & o,const A & a2) { o << a2.n; return o; } friend class MyLess; }; class MyLess { public: bool operator() (const A & a1,const A & a2) //按个位数比较大小 { return (a1.n % 10) < (a2.n % 10); } }; typedef multiset <A> MSET1; //MSET1 用“<”运算符比较大小 typedef multiset <A,MyLess> MSET2; //MSET2 用 MyLess::operator() 比较大小 int main() { const int SIZE = 6; A a[SIZE] = { 4,22,19,8,33,40 }; MSET1 m1; m1.insert(a,a + SIZE); m1.insert(22); cout << "1)" << m1.count(22) << endl; //输出 1)2 cout << "2)"; Print(m1.begin(),m1.end()); //输出 2)4 8 19 22 22 33 40 MSET1::iterator pp = m1.find(19); if (pp != m1.end()) //条件为真说明找到 cout << "found" << endl; //本行会被执行,输出 found cout << "3)"; cout << *m1.lower_bound(22) << "," << *m1.upper_bound(22) << endl; //输出 3)22,33 pp = m1.erase(m1.lower_bound(22),m1.upper_bound(22)); //pp指向被删元素的下一个元素 cout << "4)"; Print(m1.begin(),m1.end()); //输出 4)4 8 19 33 40 cout << "5)"; cout << *pp << endl; //输出 5)33 MSET2 m2; //m2中的元素按n的个位数从小到大排序 m2.insert(a,a + SIZE); cout << "6)"; Print(m2.begin(),m2.end()); //输出 6)40 22 33 4 8 19 return 0; }第 30 行,MSET2 类的排序规则和 MSET1 不同。MSET2 用 MyLess 定义排序规则,即 n 的个位数小的元素排在前面。
第 43、44 行,lower_bound 返回的迭代器指向第一个 22,upper_bound 返回的迭代器指向 33。
第 45 行,删除所有值为 22 的元素。erase 成员函数删除一个元素后,返回下一个元素的迭代器应该是很合理的,但是 C++ 标准委员会认为,返回下一个元素的迭代器也是需要时间开销的,如果程序员不想要这个返回值,那么这个开销就是浪费的——因此在遵循 C++ 标准的 Dev C++ 中,本行无法编译通过。但是微软公司认为应该对这一点做出改进,因此 Visual Studio 2010 将 erase 成员函数处理成返回被删元素下一个元素的迭代器。
不论在哪种编译器中,用 erase 成员函数删除迭代器 i 指向的元素后,迭代器 i 即告失效, 此时不能指望 ++i 后 i 会指向被删除元素的下一个元素;相反,++i 可能立即导致出错。如果想要得到被删除元素后面那个元素的迭代器,可以在删除前获取其迭代器并保存起来(这同样适用于 set、map、multimap 的 erase 成员函数)。事实上,如果得到了某关联容器的迭代器,则该迭代器并不会因为容器中元素的插入以及其他元素的删除而失效。只要该迭代器指向的元素没有被删除,就可以一直使用它。
C++/STL关联容器-集合-multiset&set的用法
C++ STL set和multiset的使用
std::set<int> s;那个s这个对象里面存贮的元素是从小到大排序的,(因为用std::less作为比较工具。)
1,set的含义是集合,它是一个有序的容器,里面的元素都是排序好的,支持插入,删除,查找等操作,就
2,Set中的元素可以是任意类型的,但是由于需要排序,所以元素必须有一个序,即大小的比较关系,比如
3,自定义比较函数;
4,set的基本操作:
begin()
clear()
count()
empty()
end()
equal_range()
erase()
find()
get_allocator() 返回集合的分配器
insert()
lower_bound()
key_comp()
max_size()
rbegin()
rend()
size()
swap()
upper_bound()
value_comp()
1:
set元素的插入:
- #include <iostream>
- #include <string>
- #include <set>
- using namespace std;
- void printSet(set<int> s)
- {
- set<int>::iterator i;
- for(i=s.begin();i!=s.end();i++)
- printf("%d ",*i);
- cout<<endl;
- }
- void main()
- {
- //创建空的set对象,元素类型为int,
- set<int> s1;
- for (int i = 0; i <5 ; i++)
- s1.insert(i*10);
- printSet(s1);
- cout<<"s1.insert(20).second = "<<endl;;
- if (s1.insert(20).second)//再次插入20
- cout<<"Insert OK!"<<endl;
- else
- cout<<"Insert Failed!"<<endl;
- cout<<"s1.insert(50).second = "<<endl;
- if (s1.insert(50).second)
- {cout<<"Insert OK!"<<endl; printSet(s1);}
- else
- cout<<"Insert Failed!"<<endl;
- pair<set<int>::iterator, bool> p;
- p = s1.insert(60);
- if (p.second)
- {cout<<"Insert OK!"<<endl; printSet(s1);}
- else
- cout<<"Insert Failed!"<<endl;
- }
- 继续更新中
2: set 的 empty erase 删除特定元素
- #include <iostream>
- #include <set>
- using namespace std;
- int main ()
- {
- set<int> myset;
- myset.insert(20);
- myset.insert(30);
- myset.insert(10);
- while (!myset.empty())
- {
- cout <<" "<< *myset.begin();
- myset.erase(myset.begin());
- }
- cout << endl;
- return 0;
- }
- //set::find
- #include <iostream>
- #include <set>
- using namespace std;
- int main ()
- {
- set<int> myset;
- set<int>::iterator it;
- for (int i=1; i<=5; i++) myset.insert(i*10); // set: 10 20 30 40 50
- it=myset.find(20);
- myset.erase (it);
- myset.erase (myset.find(40));
- myset.erase (30);
- cout << "myset contains:";
- for (it=myset.begin(); it!=myset.end(); it++)
- cout << " " << *it;
- cout << endl;
- return 0;
- }
lower_bound()返回一个 iterator 它指向在[first,last)标记的有序序列中可以插入value,而不会破坏容器顺序的第一个位置,而这个位置标记了一个大于等于value 的值。 例如,有如下序列: ia[]={12,15,17,19,20,22,23,26,29,35,40,51}; 用值21调用lower_bound(),返回一个指向22的iterator。用值22调用lower_bound(),也返回一个指向22的iterator。
iterator upper_bound( const key_type &key ):返回一个迭代器,指向键值> key的第一个元素。
- // 6.set::lower_bound/upper_bound
- #include <iostream>
- #include <set>
- using namespace std;
- int main ()
- {
- set<int> myset;
- set<int>::iterator it,itlow,itup;
- for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90
- itlow=myset.lower_bound (30); // >=
- itup=myset.upper_bound (60); // >
- printf("%d %d",*itlow,*itup); // 30 70
- return 0;
- }
- // 7.set::equal_elements
- #include <iostream>
- #include <set>
- using namespace std;
- int main ()
- {
- set<int> myset;
- pair<set<int>::iterator,set<int>::iterator> ret;
- for (int i=1; i<=5; i++) myset.insert(i*10); // set: 10 20 30 40 50
- ret = myset.equal_range(30);
- cout << "lower bound points to: " << *ret.first << endl;
- cout << "upper bound points to: " << *ret.second << endl;
- return 0;
- }
- //lower bound points to: 30
- //upper bound points to: 40
set结构体的应用
- #include<iostream>
- #include<set>
- using namespace std;
- struct haha
- {
- int a,b;
- char s;
- friend bool operator<(struct haha a,struct haha b)
- {
- return a.s<b.s;
- }
- };
- set<struct haha>element;
- int main()
- {
- struct haha a,b,c,d,t;
- a.a=1; a.s='b';
- b.a=2; b.s='c';
- c.a=4; c.s='d';
- d.a=3; d.s='a';
- element.insert(d);
- element.insert(b);
- element.insert(c);
- element.insert(a);
- set<struct haha>::iterator it;
- for(it=element.begin(); it!=element.end();it++)
- cout<<(*it).a<<" ";
- cout<<endl;
- for(it=element.begin(); it!=element.end();it++)
- cout<<(*it).s<<" ";
- }
集合的并集 交集 差集 等等
- #include<stdio.h>
- #include<string>
- #include<set>
- #include<iostream>
- #include <algorithm>//包含
- using namespace std;
- struct compare//自定义排序方式
- {
- bool operator ()(string s1,string s2)
- {
- return s1>s2;
- }///自定义一个仿函数
- };
- int main()
- {
- typedef set<string,compare> SET;
- SET s;//建立第一个集合
- s.insert(string("sfdsfd"));
- s.insert(string("apple"));
- s.insert(string("english"));
- s.insert(string("dstd"));
- cout<<"第一个集合s1为:"<<endl;
- set<string,compare>::iterator it = s.begin();
- while(it!=s.end())
- cout<<*it++<<" ";
- SET s2;//建立第二个集合
- s2.insert(string("abc"));
- s2.insert(string("apple"));
- s2.insert(string("english"));
- cout<<endl<<"第一个集合s2为:"<<endl;
- it = s2.begin();
- while(it!=s2.end())
- cout<<*it++<<" ";
- cout<<endl<<endl;
- string str[10];
- string *end =set_intersection(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//求交集,返回值指向str最后一个元素的尾端
- /*set_intersection包含于#include <algorithm> 头文件中 其中上面的不一定非要为set容器 也可以使数组 但是前提是要把2个数组都排好序才可以
- 返回值是一个指向交集序列末尾的迭代器 至于是什么迭代器与第5个参数有关 如果是数组 返回为int的迭代器 */
- cout<<"s1,s2的交集为:"<<endl;
- string *first = str;
- while(first<end)
- cout <<*first++<<" ";
- cout<<endl<<endl<<"s1,s2的并集为:"<<endl;
- end =set_union(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//并集
- first = str;
- while(first<end)
- cout <<*first++<<" ";
- cout<<endl<<endl<<"s2相对于s1的差集:"<<endl;
- first = str;
- end = std::set_difference(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//s2相对于s1的差集
- while(first<end)
- cout <<*first++<<" ";
- cout<<endl<<endl<<"s1相对于s2的差集:"<<endl;
- first = str;
- end = std::set_difference(s2.begin(),s2.end(),s.begin(),s.end(),str,compare());//s1相对于s2的差集
- while(first<end)
- cout <<*first++<<" ";
- cout<<endl<<endl;
- first = str;
- end = std::set_symmetric_difference(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//上面两个差集的并集
- while(first<end)
- cout <<*first++<<" ";
- cout<<endl;
- /*
- set<int> s3 ;
- set<int>::iterator iter = s3.begin() ;
- set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),inserter(s3,iter));
- copy(s3.begin(),s3.end(), ostream_iterator<int>(cout," "));
- */
- }
另外一个实例
- /*set_intersection()算法计算两个集合[start1, end1)和[start2, end2)的交集, 交集被储存在result中.
- 两个集合以序列的形式给出, 并且必须先按升序排好位置.
- set_intersection()的返回值是一个指向交集序列末尾的迭代器.
- set_intersection()以线性时间(linear time)运行.
- 如果严格弱排序函数对象cmp未指定, set_intersection()将使用<操作符比较元素.
- 范例
- */
- // set_intersection example
- #include <iostream>
- #include <algorithm>
- #include <vector>
- using namespace std;
- int main () {
- int first[] = {5,10,15,20,25};
- int second[] = {50,40,30,20,10};
- vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0
- vector<int>::iterator it;
- sort (first,first+5); // 5 10 15 20 25
- sort (second,second+5); // 10 20 30 40 50
- it=set_intersection (first, first+5, second, second+5, v.begin());
- // 10 20 0 0 0 0 0 0 0 0
- cout << "intersection has " << int(it - v.begin()) << " elements.\n";
- return 0;
- }
- /*输出: intersection has 2 elements*/
multiset的删除 重要