前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[动态SQL查询中的字段加密解密]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
转载文章
...aimTypes类中字段的值使用的是流行模式(Popular Schema),因此为了使Index.cshtml视图的输出更易于阅读,我在IdentityHelpers.cs文件中添加了一个HTML辅助器,如清单15-14所示。Index.cshtml文件正是使用这个辅助器格式化了Claim.Type属性的值。 Listing 15-14. Adding a Helper to the IdentityHelpers.cs File 清单15-14. 在IdentityHelpers.cs文件中添加辅助器 using System.Web;using System.Web.Mvc;using Microsoft.AspNet.Identity.Owin;using System;using System.Linq;using System.Reflection;using System.Security.Claims;namespace Users.Infrastructure {public static class IdentityHelpers {public static MvcHtmlString GetUserName(this HtmlHelper html, string id) {AppUserManager mgr= HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();return new MvcHtmlString(mgr.FindByIdAsync(id).Result.UserName);} public static MvcHtmlString ClaimType(this HtmlHelper html, string claimType) {FieldInfo[] fields = typeof(ClaimTypes).GetFields();foreach (FieldInfo field in fields) {if (field.GetValue(null).ToString() == claimType) {return new MvcHtmlString(field.Name);} }return new MvcHtmlString(string.Format("{0}",claimType.Split('/', '.').Last()));} }} Note The helper method isn’t at all efficient because it reflects on the fields of the ClaimType class for each claim that is displayed, but it is sufficient for my purposes in this chapter. You won’t often need to display the claim type in real applications. 注:该辅助器并非十分有效,因为它只是针对每个要显示的声明(Claim)映射出ClaimType类的字段,但对我要的目的已经足够了。在实际项目中不会经常需要显示声明(Claim)的类型。 To see why I have created a controller that uses claims without really explaining what they are, start the application, authenticate as the user Alice (with the password MySecret), and request the /Claims/Index URL. Figure 15-5 shows the content that is generated. 为了弄明白我为何要先创建一个使用声明(Claims)的控制器,而没有真正解释声明(Claims)是什么的原因,可以启动应用程序,以用户Alice进行认证(其口令是MySecret),并请求/Claims/Index URL。图15-5显示了生成的内容。 Figure 15-5. The output from the Index action of the Claims controller 图15-5. Claims控制器中Index动作的输出 It can be hard to make out the detail in the figure, so I have reproduced the content in Table 15-7. 这可能还难以认识到此图的细节,为此我在表15-7中重列了其内容。 Table 15-7. The Data Shown in Figure 15-5 表15-7. 图15-5中显示的数据 Subject(科目) Issuer(发行者) Type(类型) Value(值) Alice LOCAL AUTHORITY SecurityStamp Unique ID Alice LOCAL AUTHORITY IdentityProvider ASP.NET Identity Alice LOCAL AUTHORITY Role Employees Alice LOCAL AUTHORITY Role Users Alice LOCAL AUTHORITY Name Alice Alice LOCAL AUTHORITY NameIdentifier Alice’s user ID The table shows the most important aspect of claims, which is that I have already been using them when I implemented the traditional authentication and authorization features in Chapter 14. You can see that some of the claims relate to user identity (the Name claim is Alice, and the NameIdentifier claim is Alice’s unique user ID in my ASP.NET Identity database). 此表展示了声明(Claims)最重要的方面,这些是我在第14章中实现传统的认证和授权特性时,一直在使用的信息。可以看出,有些声明(Claims)与用户标识有关(Name声明是Alice,NameIdentifier声明是Alice在ASP.NET Identity数据库中的唯一用户ID号)。 Other claims show membership of roles—there are two Role claims in the table, reflecting the fact that Alice is assigned to both the Users and Employees roles. There is also a claim about how Alice has been authenticated: The IdentityProvider is set to ASP.NET Identity. 其他声明(Claims)显示了角色成员——表中有两个Role声明(Claim),体现出Alice被赋予了Users和Employees两个角色这一事实。还有一个是Alice已被认证的声明(Claim):IdentityProvider被设置到了ASP.NET Identity。 The difference when this information is expressed as a set of claims is that you can determine where the data came from. The Issuer property for all the claims shown in the table is set to LOCAL AUTHORITY, which indicates that the user’s identity has been established by the application. 当这种信息被表示成一组声明(Claims)时的差别是,你能够确定这些数据是从哪里来的。表中所显示的所有声明的Issuer属性(发布者)都被设置到了LOACL AUTHORITY(本地授权),这说明该用户的标识是由应用程序建立的。 So, now that you have seen some example claims, I can more easily describe what a claim is. A claim is any piece of information about a user that is available to the application, including the user’s identity and role memberships. And, as you have seen, the information I have been defining about my users in earlier chapters is automatically made available as claims by ASP.NET Identity. 因此,现在你已经看到了一些声明(Claims)示例,我可以更容易地描述声明(Claim)是什么了。一项声明(Claim)是可用于应用程序中的有关用户的一个信息片段,包括用户的标识以及角色成员等。而且,正如你所看到的,我在前几章定义的关于用户的信息,被ASP.NET Identity自动地作为声明(Claims)了。 15.3.2 Creating and Using Claims 15.3.2 创建和使用声明(Claims) Claims are interesting for two reasons. The first reason is that an application can obtain claims from multiple sources, rather than just relying on a local database for information about the user. You will see a real example of this when I show you how to authenticate users through a third-party system in the “Using Third-Party Authentication” section, but for the moment I am going to add a class to the example project that simulates a system that provides claims information. Listing 15-15 shows the contents of the LocationClaimsProvider.cs file that I added to the Infrastructure folder. 声明(Claims)比较有意思的原因有两个。第一个原因是应用程序可以从多个来源获取声明(Claims),而不是只能依靠本地数据库关于用户的信息。你将会看到一个实际的示例,在“使用第三方认证”小节中,将演示如何通过第三方系统来认证用户。不过,此刻我只打算在示例项目中添加一个类,用以模拟一个提供声明(Claims)信息的系统。清单15-15显示了我添加到Infrastructure文件夹中LocationClaimsProvider.cs文件的内容。 Listing 15-15. The Contents of the LocationClaimsProvider.cs File 清单15-15. LocationClaimsProvider.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public static class LocationClaimsProvider {public static IEnumerable<Claim> GetClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.Name.ToLower() == "alice") {claims.Add(CreateClaim(ClaimTypes.PostalCode, "DC 20500"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "DC"));} else {claims.Add(CreateClaim(ClaimTypes.PostalCode, "NY 10036"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "NY"));}return claims;}private static Claim CreateClaim(string type, string value) {return new Claim(type, value, ClaimValueTypes.String, "RemoteClaims");} }} The GetClaims method takes a ClaimsIdentity argument and uses the Name property to create claims about the user’s ZIP code and state. This class allows me to simulate a system such as a central HR database, which would be the authoritative source of location information about staff, for example. GetClaims方法以ClaimsIdentity为参数,并使用Name属性创建了关于用户ZIP码(邮政编码)和州府的声明(Claims)。上述这个类使我能够模拟一个诸如中心化的HR数据库(人力资源数据库)之类的系统,它可能会成为全体职员的地点信息的权威数据源。 Claims are associated with the user’s identity during the authentication process, and Listing 15-16 shows the changes I made to the Login action method of the Account controller to call the LocationClaimsProvider class. 在认证过程期间,声明(Claims)是与用户标识关联在一起的,清单15-16显示了我对Account控制器中Login动作方法所做的修改,以便调用LocationClaimsProvider类。 Listing 15-16. Associating Claims with a User in the AccountController.cs File 清单15-16. AccountController.cs文件中用户用声明的关联 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... You can see the effect of the location claims by starting the application, authenticating as a user, and requesting the /Claim/Index URL. Figure 15-6 shows the claims for Alice. You may have to sign out and sign back in again to see the change. 为了看看这个地点声明(Claims)的效果,可以启动应用程序,以一个用户进行认证,并请求/Claim/Index URL。图15-6显示了Alice的声明(Claims)。你可能需要退出,然后再次登录才会看到发生的变化。 Figure 15-6. Defining additional claims for users 图15-6. 定义用户的附加声明 Obtaining claims from multiple locations means that the application doesn’t have to duplicate data that is held elsewhere and allows integration of data from external parties. The Claim.Issuer property tells you where a claim originated from, which helps you judge how accurate the data is likely to be and how much weight you should give the data in your application. Location data obtained from a central HR database is likely to be more accurate and trustworthy than data obtained from an external mailing list provider, for example. 从多个地点获取声明(Claims)意味着应用程序不必复制其他地方保持的数据,并且能够与外部的数据集成。Claim.Issuer属性(图15-6中的Issuer数据列——译者注)能够告诉你一个声明(Claim)的发源地,这有助于让你判断数据的精确程度,也有助于让你决定这类数据在应用程序中的权重。例如,从中心化的HR数据库获取的地点数据可能要比外部邮件列表提供器获取的数据更为精确和可信。 1. Applying Claims 1. 运用声明(Claims) The second reason that claims are interesting is that you can use them to manage user access to your application more flexibly than with standard roles. The problem with roles is that they are static, and once a user has been assigned to a role, the user remains a member until explicitly removed. This is, for example, how long-term employees of big corporations end up with incredible access to internal systems: They are assigned the roles they require for each new job they get, but the old roles are rarely removed. (The unexpectedly broad systems access sometimes becomes apparent during the investigation into how someone was able to ship the contents of the warehouse to their home address—true story.) 声明(Claims)有意思的第二个原因是,你可以用它们来管理用户对应用程序的访问,这要比标准的角色管理更为灵活。角色的问题在于它们是静态的,而且一旦用户已经被赋予了一个角色,该用户便是一个成员,直到明确地删除为止。例如,这意味着大公司的长期雇员,对内部系统的访问会十分惊人:他们每次在获得新工作时,都会赋予所需的角色,但旧角色很少被删除。(在调查某人为何能够将仓库里的东西发往他的家庭地址过程中发现,有时会出现异常宽泛的系统访问——真实的故事) Claims can be used to authorize users based directly on the information that is known about them, which ensures that the authorization changes when the data changes. The simplest way to do this is to generate Role claims based on user data that are then used by controllers to restrict access to action methods. Listing 15-17 shows the contents of the ClaimsRoles.cs file that I added to the Infrastructure. 声明(Claims)可以直接根据用户已知的信息对用户进行授权,这能够保证当数据发生变化时,授权也随之而变。此事最简单的做法是根据用户数据来生成Role声明(Claim),然后由控制器用来限制对动作方法的访问。清单15-17显示了我添加到Infrastructure中的ClaimsRoles.cs文件的内容。 Listing 15-17. The Contents of the ClaimsRoles.cs File 清单15-17. ClaimsRoles.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public class ClaimsRoles {public static IEnumerable<Claim> CreateRolesFromClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.HasClaim(x => x.Type == ClaimTypes.StateOrProvince&& x.Issuer == "RemoteClaims" && x.Value == "DC")&& user.HasClaim(x => x.Type == ClaimTypes.Role&& x.Value == "Employees")) {claims.Add(new Claim(ClaimTypes.Role, "DCStaff"));}return claims;} }} The gnarly looking CreateRolesFromClaims method uses lambda expressions to determine whether the user has a StateOrProvince claim from the RemoteClaims issuer with a value of DC and a Role claim with a value of Employees. If the user has both claims, then a Role claim is returned for the DCStaff role. Listing 15-18 shows how I call the CreateRolesFromClaims method from the Login action in the Account controller. CreateRolesFromClaims是一个粗糙的考察方法,它使用了Lambda表达式,以检查用户是否具有StateOrProvince声明(Claim),该声明来自于RemoteClaims发行者(Issuer),值为DC。也检查用户是否具有Role声明(Claim),其值为Employees。如果用户这两个声明都有,那么便返回一个DCStaff角色的Role声明。清单15-18显示了如何在Account控制器中的Login动作中调用CreateRolesFromClaims方法。 Listing 15-18. Generating Roles Based on Claims in the AccountController.cs File 清单15-18. 在AccountController.cs中根据声明生成角色 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(LocationClaimsProvider.GetClaims(ident)); ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... I can then restrict access to an action method based on membership of the DCStaff role. Listing 15-19 shows a new action method I added to the Claims controller to which I have applied the Authorize attribute. 然后我可以根据DCStaff角色的成员,来限制对一个动作方法的访问。清单15-19显示了在Claims控制器中添加的一个新的动作方法,在该方法上已经运用了Authorize注解属性。 Listing 15-19. Adding a New Action Method to the ClaimsController.cs File 清单15-19. 在ClaimsController.cs文件中添加一个新的动作方法 using System.Security.Claims;using System.Web;using System.Web.Mvc;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [Authorize(Roles="DCStaff")]public string OtherAction() {return "This is the protected action";} }} Users will be able to access OtherAction only if their claims grant them membership to the DCStaff role. Membership of this role is generated dynamically, so a change to the user’s employment status or location information will change their authorization level. 只要用户的声明(Claims)承认他们是DCStaff角色的成员,那么他们便能访问OtherAction动作。该角色的成员是动态生成的,因此,若是用户的雇用状态或地点信息发生变化,也会改变他们的授权等级。 提示:请读者从这个例子中吸取其中的思想精髓。对于读物的理解程度,仁者见仁,智者见智,能领悟多少,全凭各人,译者感觉这里的思想有无数的可能。举例说明:(1)可以根据用户的身份进行授权,比如学生在校时是“学生”,毕业后便是“校友”;(2)可以根据用户所处的部门进行授权,人事部用户属于人事团队,销售部用户属于销售团队,各团队有其自己的应用;(3)下一小节的示例是根据用户的地点授权。简言之:一方面用户的各种声明(Claim)都可以用来进行授权;另一方面用户的声明(Claim)又是可以自定义的。于是可能的运用就无法估计了。总之一句话,这种基于声明的授权(Claims-Based Authorization)有无限可能!要是没有我这里的提示,是否所有读者在此处都会有所体会?——译者注 15.3.3 Authorizing Access Using Claims 15.3.3 使用声明(Claims)授权访问 The previous example is an effective demonstration of how claims can be used to keep authorizations fresh and accurate, but it is a little indirect because I generate roles based on claims data and then enforce my authorization policy based on the membership of that role. A more direct and flexible approach is to enforce authorization directly by creating a custom authorization filter attribute. Listing 15-20 shows the contents of the ClaimsAccessAttribute.cs file, which I added to the Infrastructure folder and used to create such a filter. 前面的示例有效地演示了如何用声明(Claims)来保持新鲜和准确的授权,但有点不太直接,因为我要根据声明(Claims)数据来生成了角色,然后强制我的授权策略基于角色成员。一个更直接且灵活的办法是直接强制授权,其做法是创建一个自定义的授权过滤器注解属性。清单15-20演示了ClaimsAccessAttribute.cs文件的内容,我将它添加在Infrastructure文件夹中,并用它创建了这种过滤器。 Listing 15-20. The Contents of the ClaimsAccessAttribute.cs File 清单15-20. ClaimsAccessAttribute.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Infrastructure {public class ClaimsAccessAttribute : AuthorizeAttribute {public string Issuer { get; set; }public string ClaimType { get; set; }public string Value { get; set; }protected override bool AuthorizeCore(HttpContextBase context) {return context.User.Identity.IsAuthenticated&& context.User.Identity is ClaimsIdentity&& ((ClaimsIdentity)context.User.Identity).HasClaim(x =>x.Issuer == Issuer && x.Type == ClaimType && x.Value == Value);} }} The attribute I have defined is derived from the AuthorizeAttribute class, which makes it easy to create custom authorization policies in MVC framework applications by overriding the AuthorizeCore method. My implementation grants access if the user is authenticated, the IIdentity implementation is an instance of ClaimsIdentity, and the user has a claim with the issuer, type, and value matching the class properties. Listing 15-21 shows how I applied the attribute to the Claims controller to authorize access to the OtherAction method based on one of the location claims created by the LocationClaimsProvider class. 我所定义的这个注解属性派生于AuthorizeAttribute类,通过重写AuthorizeCore方法,很容易在MVC框架应用程序中创建自定义的授权策略。在这个实现中,若用户是已认证的、其IIdentity实现是一个ClaimsIdentity实例,而且该用户有一个带有issuer、type以及value的声明(Claim),它们与这个类的属性是匹配的,则该用户便是允许访问的。清单15-21显示了如何将这个注解属性运用于Claims控制器,以便根据LocationClaimsProvider类创建的地点声明(Claim),对OtherAction方法进行授权访问。 Listing 15-21. Performing Authorization on Claims in the ClaimsController.cs File 清单15-21. 在ClaimsController.cs文件中执行基于声明的授权 using System.Security.Claims;using System.Web;using System.Web.Mvc;using Users.Infrastructure;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [ClaimsAccess(Issuer="RemoteClaims", ClaimType=ClaimTypes.PostalCode,Value="DC 20500")]public string OtherAction() {return "This is the protected action";} }} My authorization filter ensures that only users whose location claims specify a ZIP code of DC 20500 can invoke the OtherAction method. 这个授权过滤器能够确保只有地点声明(Claim)的邮编为DC 20500的用户才能请求OtherAction方法。 15.4 Using Third-Party Authentication 15.4 使用第三方认证 One of the benefits of a claims-based system such as ASP.NET Identity is that any of the claims can come from an external system, even those that identify the user to the application. This means that other systems can authenticate users on behalf of the application, and ASP.NET Identity builds on this idea to make it simple and easy to add support for authenticating users through third parties such as Microsoft, Google, Facebook, and Twitter. 基于声明的系统,如ASP.NET Identity,的好处之一是任何声明都可以来自于外部系统,即使是将用户标识到应用程序的那些声明。这意味着其他系统可以代表应用程序来认证用户,而ASP.NET Identity就建立在这样的思想之上,使之能够简单而方便地添加第三方认证用户的支持,如微软、Google、Facebook、Twitter等。 There are some substantial benefits of using third-party authentication: Many users will already have an account, users can elect to use two-factor authentication, and you don’t have to manage user credentials in the application. In the sections that follow, I’ll show you how to set up and use third-party authentication for Google users, which Table 15-8 puts into context. 使用第三方认证有一些实际的好处:许多用户已经有了账号、用户可以选择使用双因子认证、你不必在应用程序中管理用户凭据等等。在以下小节中,我将演示如何为Google用户建立并使用第三方认证,表15-8描述了事情的情形。 Table 15-8. Putting Third-Party Authentication in Context 表15-8. 第三方认证情形 Question 问题 Answer 回答 What is it? 什么是第三方认证? Authenticating with third parties lets you take advantage of the popularity of companies such as Google and Facebook. 第三方认证使你能够利用流行公司,如Google和Facebook,的优势。 Why should I care? 为何要关心它? Users don’t like having to remember passwords for many different sites. Using a provider with large-scale adoption can make your application more appealing to users of the provider’s services. 用户不喜欢记住许多不同网站的口令。使用大范围适应的提供器可使你的应用程序更吸引有提供器服务的用户。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework. 这不是一个直接由MVC框架使用的特性。 Note The reason I have chosen to demonstrate Google authentication is that it is the only option that doesn’t require me to register my application with the authentication service. You can get details of the registration processes required at http://bit.ly/1cqLTrE. 提示:我选择演示Google认证的原因是,它是唯一不需要在其认证服务中注册我应用程序的公司。有关认证服务注册过程的细节,请参阅http://bit.ly/1cqLTrE。 15.4.1 Enabling Google Authentication 15.4.1 启用Google认证 ASP.NET Identity comes with built-in support for authenticating users through their Microsoft, Google, Facebook, and Twitter accounts as well more general support for any authentication service that supports OAuth. The first step is to add the NuGet package that includes the Google-specific additions for ASP.NET Identity. Enter the following command into the Package Manager Console: ASP.NET Identity带有通过Microsoft、Google、Facebook以及Twitter账号认证用户的内建支持,并且对于支持OAuth的认证服务具有更普遍的支持。第一个步骤是添加NuGet包,包中含有用于ASP.NET Identity的Google专用附件。请在“Package Manager Console(包管理器控制台)”中输入以下命令: Install-Package Microsoft.Owin.Security.Google -version 2.0.2 There are NuGet packages for each of the services that ASP.NET Identity supports, as described in Table 15-9. 对于ASP.NET Identity支持的每一种服务都有相应的NuGet包,如表15-9所示。 Table 15-9. The NuGet Authenticaton Packages 表15-9. NuGet认证包 Name 名称 Description 描述 Microsoft.Owin.Security.Google Authenticates users with Google accounts 用Google账号认证用户 Microsoft.Owin.Security.Facebook Authenticates users with Facebook accounts 用Facebook账号认证用户 Microsoft.Owin.Security.Twitter Authenticates users with Twitter accounts 用Twitter账号认证用户 Microsoft.Owin.Security.MicrosoftAccount Authenticates users with Microsoft accounts 用Microsoft账号认证用户 Microsoft.Owin.Security.OAuth Authenticates users against any OAuth 2.0 service 根据任一OAuth 2.0服务认证用户 Once the package is installed, I enable support for the authentication service in the OWIN startup class, which is defined in the App_Start/IdentityConfig.cs file in the example project. Listing 15-22 shows the change that I have made. 一旦安装了这个包,便可以在OWIN启动类中启用此项认证服务的支持,启动类的定义在示例项目的App_Start/IdentityConfig.cs文件中。清单15-22显示了所做的修改。 Listing 15-22. Enabling Google Authentication in the IdentityConfig.cs File 清单15-22. 在IdentityConfig.cs文件中启用Google认证 using Microsoft.AspNet.Identity;using Microsoft.Owin;using Microsoft.Owin.Security.Cookies;using Owin;using Users.Infrastructure;using Microsoft.Owin.Security.Google;namespace Users {public class IdentityConfig {public void Configuration(IAppBuilder app) {app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions {AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),}); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);app.UseGoogleAuthentication();} }} Each of the packages that I listed in Table 15-9 contains an extension method that enables the corresponding service. The extension method for the Google service is called UseGoogleAuthentication, and it is called on the IAppBuilder implementation that is passed to the Configuration method. 表15-9所列的每个包都含有启用相应服务的扩展方法。用于Google服务的扩展方法名称为UseGoogleAuthentication,它通过传递给Configuration方法的IAppBuilder实现进行调用。 Next I added a button to the Views/Account/Login.cshtml file, which allows users to log in via Google. You can see the change in Listing 15-23. 下一步骤是在Views/Account/Login.cshtml文件中添加一个按钮,让用户能够通过Google进行登录。所做的修改如清单15-23所示。 Listing 15-23. Adding a Google Login Button to the Login.cshtml File 清单15-23. 在Login.cshtml文件中添加Google登录按钮 @model Users.Models.LoginModel@{ ViewBag.Title = "Login";}<h2>Log In</h2> @Html.ValidationSummary()@using (Html.BeginForm()) {@Html.AntiForgeryToken();<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><div class="form-group"><label>Name</label>@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })</div><div class="form-group"><label>Password</label>@Html.PasswordFor(x => x.Password, new { @class = "form-control" })</div><button class="btn btn-primary" type="submit">Log In</button>}@using (Html.BeginForm("GoogleLogin", "Account")) {<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><button class="btn btn-primary" type="submit">Log In via Google</button>} The new button submits a form that targets the GoogleLogin action on the Account controller. You can see this method—and the other changes I made the controller—in Listing 15-24. 新按钮递交一个表单,目标是Account控制器中的GoogleLogin动作。可从清单15-24中看到该方法,以及在控制器中所做的其他修改。 Listing 15-24. Adding Support for Google Authentication to the AccountController.cs File 清单15-24. 在AccountController.cs文件中添加Google认证支持 using System.Threading.Tasks;using System.Web.Mvc;using Users.Models;using Microsoft.Owin.Security;using System.Security.Claims;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Infrastructure;using System.Web; namespace Users.Controllers {[Authorize]public class AccountController : Controller {[AllowAnonymous]public ActionResult Login(string returnUrl) {if (HttpContext.User.Identity.IsAuthenticated) {return View("Error", new string[] { "Access Denied" });}ViewBag.returnUrl = returnUrl;return View();}[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident)); AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);} [HttpPost][AllowAnonymous]public ActionResult GoogleLogin(string returnUrl) {var properties = new AuthenticationProperties {RedirectUri = Url.Action("GoogleLoginCallback",new { returnUrl = returnUrl})};HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();}[AllowAnonymous]public async Task<ActionResult> GoogleLoginCallback(string returnUrl) {ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();AppUser user = await UserManager.FindAsync(loginInfo.Login);if (user == null) {user = new AppUser {Email = loginInfo.Email,UserName = loginInfo.DefaultUserName,City = Cities.LONDON, Country = Countries.UK};IdentityResult result = await UserManager.CreateAsync(user);if (!result.Succeeded) {return View("Error", result.Errors);} else {result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);if (!result.Succeeded) {return View("Error", result.Errors);} }}ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false }, ident);return Redirect(returnUrl ?? "/");}[Authorize]public ActionResult Logout() {AuthManager.SignOut();return RedirectToAction("Index", "Home");}private IAuthenticationManager AuthManager {get {return HttpContext.GetOwinContext().Authentication;} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } The GoogleLogin method creates an instance of the AuthenticationProperties class and sets the RedirectUri property to a URL that targets the GoogleLoginCallback action in the same controller. The next part is a magic phrase that causes ASP.NET Identity to respond to an unauthorized error by redirecting the user to the Google authentication page, rather than the one defined by the application: GoogleLogin方法创建了AuthenticationProperties类的一个实例,并为RedirectUri属性设置了一个URL,其目标为同一控制器中的GoogleLoginCallback动作。下一个部分是一个神奇阶段,通过将用户重定向到Google认证页面,而不是应用程序所定义的认证页面,让ASP.NET Identity对未授权的错误进行响应: ...HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();... This means that when the user clicks the Log In via Google button, their browser is redirected to the Google authentication service and then redirected back to the GoogleLoginCallback action method once they are authenticated. 这意味着,当用户通过点击Google按钮进行登录时,浏览器被重定向到Google的认证服务,一旦在那里认证之后,便被重定向回GoogleLoginCallback动作方法。 I get details of the external login by calling the GetExternalLoginInfoAsync of the IAuthenticationManager implementation, like this: 我通过调用IAuthenticationManager实现的GetExternalLoginInfoAsync方法,我获得了外部登录的细节,如下所示: ...ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();... The ExternalLoginInfo class defines the properties shown in Table 15-10. ExternalLoginInfo类定义的属性如表15-10所示: Table 15-10. The Properties Defined by the ExternalLoginInfo Class 表15-10. ExternalLoginInfo类所定义的属性 Name 名称 Description 描述 DefaultUserName Returns the username 返回用户名 Email Returns the e-mail address 返回E-mail地址 ExternalIdentity Returns a ClaimsIdentity that identities the user 返回标识该用户的ClaimsIdentity Login Returns a UserLoginInfo that describes the external login 返回描述外部登录的UserLoginInfo I use the FindAsync method defined by the user manager class to locate the user based on the value of the ExternalLoginInfo.Login property, which returns an AppUser object if the user has been authenticated with the application before: 我使用了由用户管理器类所定义的FindAsync方法,以便根据ExternalLoginInfo.Login属性的值对用户进行定位,如果用户之前在应用程序中已经认证,该属性会返回一个AppUser对象: ...AppUser user = await UserManager.FindAsync(loginInfo.Login);... If the FindAsync method doesn’t return an AppUser object, then I know that this is the first time that this user has logged into the application, so I create a new AppUser object, populate it with values, and save it to the database. I also save details of how the user logged in so that I can find them next time: 如果FindAsync方法返回的不是AppUser对象,那么我便知道这是用户首次登录应用程序,于是便创建了一个新的AppUser对象,填充该对象的值,并将其保存到数据库。我还保存了用户如何登录的细节,以便下次能够找到他们: ...result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);... All that remains is to generate an identity the user, copy the claims provided by Google, and create an authentication cookie so that the application knows the user has been authenticated: 剩下的事情只是生成该用户的标识了,拷贝Google提供的声明(Claims),并创建一个认证Cookie,以使应用程序知道此用户已认证: ...ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);... 15.4.2 Testing Google Authentication 15.4.2 测试Google认证 There is one further change that I need to make before I can test Google authentication: I need to change the account verification I set up in Chapter 13 because it prevents accounts from being created with e-mail addresses that are not within the example.com domain. Listing 15-25 shows how I removed the verification from the AppUserManager class. 在测试Google认证之前还需要一处修改:需要修改第13章所建立的账号验证,因为它不允许example.com域之外的E-mail地址创建账号。清单15-25显示了如何在AppUserManager类中删除这种验证。 Listing 15-25. Disabling Account Validation in the AppUserManager.cs File 清单15-25. 在AppUserManager.cs文件中取消账号验证 using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Microsoft.AspNet.Identity.Owin;using Microsoft.Owin;using Users.Models; namespace Users.Infrastructure {public class AppUserManager : UserManager<AppUser> {public AppUserManager(IUserStore<AppUser> store): base(store) {}public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options,IOwinContext context) {AppIdentityDbContext db = context.Get<AppIdentityDbContext>();AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db)); manager.PasswordValidator = new CustomPasswordValidator {RequiredLength = 6,RequireNonLetterOrDigit = false,RequireDigit = false,RequireLowercase = true,RequireUppercase = true}; //manager.UserValidator = new CustomUserValidator(manager) {// AllowOnlyAlphanumericUserNames = true,// RequireUniqueEmail = true//};return manager;} }} Tip you can use validation for externally authenticated accounts, but I am just going to disable the feature for simplicity. 提示:也可以使用外部已认证账号的验证,但这里出于简化,取消了这一特性。 To test authentication, start the application, click the Log In via Google button, and provide the credentials for a valid Google account. When you have completed the authentication process, your browser will be redirected back to the application. If you navigate to the /Claims/Index URL, you will be able to see how claims from the Google system have been added to the user’s identity, as shown in Figure 15-7. 为了测试认证,启动应用程序,通过点击“Log In via Google(通过Google登录)”按钮,并提供有效的Google账号凭据。当你完成了认证过程时,浏览器将被重定向回应用程序。如果导航到/Claims/Index URL,便能够看到来自Google系统的声明(Claims),已被添加到用户的标识中了,如图15-7所示。 Figure 15-7. Claims from Google 图15-7. 来自Google的声明(Claims) 15.5 Summary 15.5 小结 In this chapter, I showed you some of the advanced features that ASP.NET Identity supports. I demonstrated the use of custom user properties and how to use database migrations to preserve data when you upgrade the schema to support them. I explained how claims work and how they can be used to create more flexible ways of authorizing users. I finished the chapter by showing you how to authenticate users via Google, which builds on the ideas behind the use of claims. 本章向你演示了ASP.NET Identity所支持的一些高级特性。演示了自定义用户属性的使用,还演示了在升级数据架构时,如何使用数据库迁移保护数据。我解释了声明(Claims)的工作机制,以及如何将它们用于创建更灵活的用户授权方式。最后演示了如何通过Google进行认证结束了本章,这是建立在使用声明(Claims)的思想基础之上的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-28 08:49:21
283
转载
Sqoop
...用场景 Sqoop(SQL-to-Hadoop)作为一款强大的数据迁移工具,主要用于在关系型数据库(如MySQL、Oracle等)和Hadoop生态组件(如HDFS、Hive等)间进行高效的数据导入导出操作。不过在实际操作的时候,由于各家数据库系统对数据类型的定义各不相同,Sqoop这家伙在处理一些特定的数据库表字段类型时,可能就会尥蹶子,给你抛出个ClassNotFoundException异常来。 2. “ClassNotFoundException”问题浅析 场景还原: 假设我们有一个MySQL数据库表,其中包含一种自定义的列类型MEDIUMBLOB。当尝试使用Sqoop将其导入到HDFS或Hive时,可能会遭遇如下错误: bash java.lang.ClassNotFoundException: com.mysql.jdbc.MySQLBlobInputStream 这是因为Sqoop在默认配置下可能并不支持所有数据库特定的内置类型,尤其是那些非标准的或者用户自定义的类型。 3. 解决方案详述 3.1 自定义jdbc驱动类映射 为了解决上述问题,我们需要帮助Sqoop识别并正确处理这些特定的列类型。Sqoop这个工具超级贴心,它让用户能够自由定制JDBC驱动的类映射。你只需要在命令行耍个“小魔法”,也就是加上--map-column-java这个参数,就能轻松指定源表中特定列在Java环境下的对应类型啦,就像给不同数据类型找到各自合适的“变身衣裳”一样。 例如,对于上述的MEDIUMBLOB类型,我们可以将其映射为Java的BytesWritable类型: bash sqoop import \ --connect jdbc:mysql://localhost/mydatabase \ --table my_table \ --columns 'id, medium_blob_column' \ --map-column-java medium_blob_column=BytesWritable \ --target-dir /user/hadoop/my_table_data 3.2 扩展Sqoop的JDBC驱动 另一种更为复杂但更为彻底的方法是扩展Sqoop的JDBC驱动,实现对特定类型的支持。通常来说,这意味着你需要亲自操刀,写一个定制版的JDBC驱动程序。这个驱动要能“接班” Sqoop自带的那个驱动,专门对付那些原生驱动搞不定的数据类型转换问题。 java // 这是一个简化的示例,实际操作中需要对接具体的数据库API public class CustomMySQLDriver extends com.mysql.jdbc.Driver { // 重写方法以支持对MEDIUMBLOB类型的处理 @Override public java.sql.ResultSetMetaData getMetaData(java.sql.Connection connection, java.sql.Statement statement, String sql) throws SQLException { ResultSetMetaData metadata = super.getMetaData(connection, statement, sql); // 对于MEDIUMBLOB类型的列,返回对应的Java类型 for (int i = 1; i <= metadata.getColumnCount(); i++) { if ("MEDIUMBLOB".equals(metadata.getColumnTypeName(i))) { metadata.getColumnClassName(i); // 返回"java.sql.Blob" } } return metadata; } } 然后在Sqoop命令行中引用这个自定义的驱动: bash sqoop import \ --driver com.example.CustomMySQLDriver \ ... 4. 思考与讨论 尽管Sqoop在大多数情况下可以很好地处理数据迁移任务,但在面对一些特殊的数据库表列类型时,我们仍需灵活应对。无论是对JDBC驱动进行小幅度的类映射微调,还是大刀阔斧地深度定制,最重要的一点,就是要摸透Sqoop的工作机制,搞清楚它背后是怎么通过底层的JDBC接口,把那些Java对象两者之间巧妙地对应和映射起来的。想要真正玩转那个功能强大的Sqoop数据迁移神器,就得在实际操作中不断摸爬滚打、学习积累。这样,才能避免被“ClassNotFoundException”这类让人头疼的小插曲绊住手脚,顺利推进工作进程。
2023-04-02 14:43:37
83
风轻云淡
Golang
...关系型数据库或者NoSQL数据库。在这里,我们将重点介绍如何使用Golang与MySQL数据库进行交互。 四、Go与MySQL的连接 首先,我们需要引入“database/sql”包,这个包包含了对SQL数据库的基本操作。然后,我们需要创建一个函数来初始化数据库连接。 go import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) func initDB() (sql.DB, error) { db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname") if err != nil { return nil, err } return db, nil } 五、插入数据 接下来,我们就可以开始使用连接来进行数据的插入操作了。下面是一个简单的例子: go db, err := initDB() if err != nil { panic(err.Error()) } defer db.Close() _, err = db.Exec("INSERT INTO users (username, password) VALUES (?, ?)", "john", "$2a$10$B8AIFbLlWz2fPnZrjL9wmuPfYmV5XKpQyvJ7UeV9nGZIvnpOKwldO.") if err != nil { panic(err.Error()) } 六、查询数据 除了插入数据,我们还需要能够从数据库中查询数据。同样,这也很简单。下面是一个查询的例子: go db, err := initDB() if err != nil { panic(err.Error()) } defer db.Close() rows, err := db.Query("SELECT FROM users WHERE username = ?", "john") if err != nil { panic(err.Error()) } defer rows.Close() for rows.Next() { var username string var password string err = rows.Scan(&username, &password) if err != nil { panic(err.Error()) } fmt.Println(username, password) } 七、总结 通过以上内容,我们可以看出,使用Golang与MySQL进行数据持久化是非常容易的。只需要引入必要的库,就可以开始编写相关的代码了。而且,你知道吗,正因为Golang的独特优势,我们能够编写出超级高效、超稳可靠的代码!所以,如果你正在寻觅一种崭新的法子来搞定数据的长期存储问题,那么我真心推荐你试一试Golang,它绝对会让你眼前一亮!
2023-03-23 17:32:03
468
冬日暖阳-t
转载文章
...TreeNode("查询用户"); DefaultMutableTreeNode dmtn_jieyue = new DefaultMutableTreeNode("借阅管理"); DefaultMutableTreeNode dmtn_jieyue_insert = new DefaultMutableTreeNode("增加借阅信息"); DefaultMutableTreeNode dmtn_jieyue_update = new DefaultMutableTreeNode("修改借阅信息"); DefaultMutableTreeNode dmtn_jieyue_delete = new DefaultMutableTreeNode("删除借阅信息"); DefaultMutableTreeNode dmtn_jieyue_select = new DefaultMutableTreeNode("查询借阅信息"); dmtn_yonghu.add(dmtnQieHuan); dmtn_yonghu.add(dmtn_yonghu_insert); dmtn_yonghu.add(dmtn_yonghu_update); dmtn_yonghu.add(dmtn_yonghu_delete); dmtn_yonghu.add(dmtn_yonghu_select); dmtn_jieyue.add(dmtn_jieyue_insert); dmtn_jieyue.add(dmtn_jieyue_update); dmtn_jieyue.add(dmtn_jieyue_delete); dmtn_jieyue.add(dmtn_jieyue_select); dmtn1.add(dmtn_yonghu); dmtn1.add(dmtn_jieyue); JTree1 = new JTree(dmtn1); JTree1.addTreeSelectionListener(new swingJpanelShiJian(this)); JTree1.setBackground(Color.white); jpPinkLeft.setBackground(Color.white); //JTree1.setBounds(10,170,200,450);在这里是一句没效果的代码 jpPinkLeft.add(JTree1); this.add(jpRed);this.add(jpPinkLeft); this.add(jpGreenRightBottom2); this.add(jpBlueRightBottom1); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } class swingJpanelShiJian implements ActionListener, TreeSelectionListener{ //jieShou接收 //chuangTi窗体 public static swingJpanelQieHuan jieShou; public swingJpanelShiJian(swingJpanelQieHuan chuangTi){ jieShou=chuangTi; } @Override public void actionPerformed(ActionEvent arg0) { String neiRong=arg0.getActionCommand(); if(neiRong.equals("点赞界面")){ jieShou.jpBlueRightBottom1.setVisible(true); jieShou.jpGreenRightBottom2.setVisible(false); }else if(neiRong.equals("三连关注界面")){ jieShou.jpBlueRightBottom1.setVisible(false); jieShou.jpGreenRightBottom2.setVisible(true); } } @Override public void valueChanged(TreeSelectionEvent arg0) { DefaultMutableTreeNode str = (DefaultMutableTreeNode) jieShou.JTree1 .getLastSelectedPathComponent(); if (str.toString().equals("切换到登录界面")) { new newDengLu(); } else { } } } JTable初始化表格 package swing; public class mains { public static void main(String[] args) { new swingBiaoGe(); } } package swing; import java.util.Vector; import javax.swing.; import javax.swing.table.DefaultTableModel; public class swingBiaoGe extends JFrame{ //要声明 : 装载内容的容器,table的控件, 容器的标题, 容器的具体的内容。 public static JTable biaoGe=null;//JTable为表格的控件 //要声明装载内容的容器,如下: public static DefaultTableModel DTM=null; //Vector中: //一个放标题,一个放内容 //>表示只接受集合的类型 Vector biaoTi; Vector> neiRong; public swingBiaoGe(){ this.setLayout(null); this.setSize(600,600); this.setLocationRelativeTo(null); //给标题赋值: biaoTi=new Vector(); biaoTi.add("编号");biaoTi.add("姓名"); biaoTi.add("性别");biaoTi.add("年龄"); //给内容赋值: neiRong=new Vector>(); for(int i=0;i<5;i++){ Vector v=new Vector(); v.add("编号"+(i+6));v.add("诗书画唱"+(i+6)); v.add("性别"+(i+6));v.add("年龄"+(i+6)); neiRong.add(v); } //将内容添加到装载内容的容器中: DTM=new DefaultTableModel(neiRong,biaoTi); DTM=new DefaultTableModel(neiRong,biaoTi) { @Override public boolean isCellEditable(int a, int b) { return false; } }; biaoGe=new JTable(DTM); //设置滚动条: JScrollPane jsp=new JScrollPane(biaoGe); jsp.setBounds(10,10,400,400); this.add(jsp); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } JTable初始化数据,数据要求链接JDBC获取 create database yonghu select from shangpin; select from sp_Type; create table sp_Type( sp_TypeID int primary key identity(1,1), sp_TypeName varchar(100) not null ); insert into sp_Type values('水果'); insert into sp_Type values('零食'); insert into sp_Type values('小吃'); insert into sp_Type values('日常用品'); create table shangpin( sp_ID int primary key identity(1,1), sp_Name varchar(100) not null, sp_Price decimal(10,2) not null, sp_TypeID int, sp_Jieshao varchar(300) ); insert into shangpin values('苹果',12,1,'好吃的苹果'); insert into shangpin values('香蕉',2,1,'好吃的香蕉'); insert into shangpin values('橘子',4,1,'好吃的橘子'); insert into shangpin values('娃哈哈',3,2,'好吃营养好'); insert into shangpin values('牙刷',5,4,'全自动牙刷'); package SwingJdbc; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; public class biaoGe extends JFrame { class shiJian implements MouseListener, ActionListener { public biaoGe jieShou = null; public shiJian(biaoGe chuangTi) { this.jieShou = chuangTi; } @Override public void actionPerformed(ActionEvent arg0) { String name = jieShou.wenBenKuangName.getText(); String price = jieShou.wenBenKuangPrice.getText(); String type = jieShou.wenBenKuangTypeId.getText(); String jieshao = jieShou.wenBenKuangJieShao. getText(); String sql = "insert into shangpin values('" + name + "'" + ", " + price + "," + type + ",'" + jieshao + "')"; if (DBUtils.ZSG(sql)) { JOptionPane.showMessageDialog(null, "增加成功"); jieShou.chaxunchushihua(); } else { JOptionPane.showMessageDialog(null, "出现了未知的错误,增加失败"); } } @Override public void mouseClicked(MouseEvent arg0) { if (arg0.getClickCount() == 2) { int row = jieShou.biaoGe1.getSelectedRow(); jieShou.wenBenKuangBianHao .setText(jieShou.biaoGe1.getValueAt( row, 0).toString()); jieShou.wenBenKuangName .setText(jieShou.biaoGe1.getValueAt( row, 1).toString()); jieShou.wenBenKuangPrice .setText(jieShou.biaoGe1.getValueAt( row, 2).toString()); jieShou.wenBenKuangTypeId .setText(jieShou.biaoGe1.getValueAt( row, 3).toString()); jieShou.wenBenKuangJieShao .setText(jieShou.biaoGe1.getValueAt( row, 4).toString()); } if (arg0.isMetaDown()) { int num = JOptionPane.showConfirmDialog(null, "是否确认删除这条信息?"); if (num == 0) { int row = jieShou.biaoGe1 .getSelectedRow(); String sql = "delete shangpin where sp_id=" + jieShou.biaoGe1.getValueAt( row, 0) + ""; if (DBUtils.ZSG(sql)) { JOptionPane.showMessageDialog(null, "册除成功"); jieShou.chaxunchushihua(); } else { JOptionPane.showMessageDialog(null, "出现了未知的错误,请重试"); } } } } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } static JButton zengJiaAnNiu = null; static DefaultTableModel biaoGeMoXing1 = null; static JScrollPane gunDongTiao = null; static JTable biaoGe1 = null; static JLabel wenZiBianHao, wenZiName, wenZiPrice, wenZiTypeId, wenZiJieShao; static JTextField wenBenKuangBianHao, wenBenKuangName, wenBenKuangPrice, wenBenKuangTypeId, wenBenKuangJieShao; static Vector BiaoTiJiHe = null; static Vector> NeiRongJiHe = null; JPanel mianBan1, mianBan2 = null; public biaoGe() { this.setTitle("登录后的界面"); this.setSize(800, 600); this.setLayout(null); this.setLocationRelativeTo(null); wenZiBianHao = new JLabel("编号"); wenZiName = new JLabel("名称"); wenZiPrice = new JLabel("价格"); wenZiTypeId = new JLabel("类型ID"); wenZiJieShao = new JLabel("介绍"); zengJiaAnNiu = new JButton("添加数据"); zengJiaAnNiu.setBounds(530, 390, 100, 30); zengJiaAnNiu.addActionListener(new shiJian(this)); this.add(zengJiaAnNiu); wenZiBianHao.setBounds(560, 100, 70, 30); wenZiName.setBounds(560, 140, 70, 30); wenZiPrice.setBounds(560, 180, 70, 30); wenZiTypeId.setBounds(560, 220, 70, 30); wenZiJieShao.setBounds(560, 260, 70, 30); this.add(wenZiBianHao); this.add(wenZiName); this.add(wenZiPrice); this.add(wenZiTypeId); this.add(wenZiJieShao); wenBenKuangBianHao = new JTextField(); wenBenKuangBianHao.setEditable(false); wenBenKuangName = new JTextField(); wenBenKuangPrice = new JTextField(); wenBenKuangTypeId = new JTextField(); wenBenKuangJieShao = new JTextField(); wenBenKuangBianHao.setBounds(640, 100, 130, 30); wenBenKuangName.setBounds(640, 140, 130, 30); wenBenKuangPrice.setBounds(640, 180, 130, 30); wenBenKuangTypeId.setBounds(640, 220, 130, 30); wenBenKuangJieShao.setBounds(640, 260, 130, 30); this.add(wenBenKuangBianHao); this.add(wenBenKuangName); this.add(wenBenKuangPrice); this.add(wenBenKuangTypeId); this.add(wenBenKuangJieShao); biaoGeFengZhuangFangFa(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } //biaoGeFengZhuangFangFa表格的封装方法 private void biaoGeFengZhuangFangFa() { BiaoTiJiHe = new Vector(); BiaoTiJiHe.add("编号"); BiaoTiJiHe.add("名称"); BiaoTiJiHe.add("价格"); BiaoTiJiHe.add("类型"); BiaoTiJiHe.add("介绍"); String sql = "select from shangpin"; ResultSet res = DBUtils.Select(sql); try { NeiRongJiHe = new Vector>(); while (res.next()) { Vector v = new Vector(); v.add(res.getInt("sp_ID")); v.add(res.getString("sp_Name")); v.add(res.getDouble("sp_price")); v.add(res.getInt("sp_TypeID")); v.add(res.getString("sp_Jieshao")); NeiRongJiHe.add(v); } biaoGeMoXing1 = new DefaultTableModel(NeiRongJiHe, BiaoTiJiHe) { @Override public boolean isCellEditable(int a, int b) { return false; } }; biaoGe1 = new JTable(biaoGeMoXing1); biaoGe1.addMouseListener(new shiJian(this)); biaoGe1.setBounds(0, 0, 500, 500); gunDongTiao= new JScrollPane(biaoGe1); gunDongTiao .setBounds(0, 0, 550, 150); mianBan1 = new JPanel(); mianBan1.add(gunDongTiao ); mianBan1.setBounds(0, 0, 550, 250); this.add(mianBan1); } catch (SQLException e) { e.printStackTrace(); } } public void chaxunchushihua() { if (this.mianBan1 != null) { this.remove(mianBan1); } biaoGeFengZhuangFangFa(); // 释放资源:this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } package SwingJdbc; import java.sql.; public class DBUtils { static Connection con=null; static Statement sta=null; static ResultSet res=null; //在静态代码块中执行 static{ try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //封装链接数据库的方法 public static Connection getCon(){ if(con==null){ try { con=DriverManager.getConnection ("jdbc:sqlserver://localhost;databaseName=yonghu","qqq","123"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return con; } //查询的方法 public static ResultSet Select(String sql){ con=getCon();//建立数据库链接 try { sta=con.createStatement(); res=sta.executeQuery(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; } //增删改查的方法 //返回int类型的数据 public static boolean ZSG(String sql){ con=getCon();//建立数据库链接 boolean b=false; try { sta=con.createStatement(); int num=sta.executeUpdate(sql); //0就是没有执行成功,大于0 就成功了 if(num>0){ b=true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return b; } } package SwingJdbc; public class mains { public static void main(String[] args) { new biaoGe(); } } 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_39929646/article/details/114190817。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-18 08:36:23
525
转载
Sqoop
... 引言 Sqoop(SQL-to-Hadoop)作为大数据生态系统中的重要工具,承担着关系型数据库与Hadoop之间高效、便捷的数据迁移重任。它就像一个超级能干的“数据搬运工”,不辞辛苦地把企业那些海量的、整齐排列的数据从RDBMS这个仓库,搬到Hadoop的大数据分析基地去深度挖掘和处理;或者有时候也会反向操作,把数据从Hadoop搬回到RDBMS中。 shell 一个简单的Sqoop导入示例 sqoop import \ --connect jdbc:mysql://localhost:3306/mydatabase \ --username myuser \ --password mypassword \ --table mytable \ --target-dir /user/hadoop/mytable_imported 这个命令展示了如何从MySQL数据库导入mytable表到HDFS的/user/hadoop/mytable_imported目录下。 2. Sqoop工作原理及功能特性 (此处详细描述Sqoop的工作原理,如并行导入导出、自动生成Java类、分区导入等特性) 2.1 并行导入示例 Sqoop利用MapReduce模型实现并行数据导入,大幅提高数据迁移效率。 shell sqoop import --num-mappers 4 ... 此命令设置4个map任务并行执行数据导入操作。 3. Sqoop的基本使用 (这里详细说明Sqoop的各种命令,包括import、export、create-hive-table等,并给出实例) 3.1 Sqoop Import 实例详解 shell 示例:将Oracle表同步至Hive表 sqoop import \ --connect jdbc:oracle:thin:@//hostname:port/service_name \ --username username \ --password password \ --table source_table \ --hive-import \ --hive-table target_table 这段代码演示了如何将Oracle数据库中的source_table直接导入到Hive的target_table。 4. Sqoop高级应用与实践问题探讨 (这部分深入探讨Sqoop的一些高级用法,如增量导入、容错机制、自定义连接器等,并通过具体案例阐述) 4.1 增量导入策略 shell 使用lastmodified或incremental方式实现增量导入 sqoop import \ --connect ... \ --table source_table \ --check-column id \ --incremental lastmodified \ --last-value 这段代码展示了如何根据最后一次导入的id值进行增量导入。 5. Sqoop在实际业务场景中的应用与挑战 (在这部分,我们可以探讨Sqoop在真实业务环境下的应用场景,以及可能遇到的问题及其解决方案) 以上仅为大纲及部分内容展示,实际上每部分都需要进一步拓展、深化和情感化的表述,使读者能更好地理解Sqoop的工作机制,掌握其使用方法,并能在实际工作中灵活运用。为了达到1000字以上的要求,每个章节都需要充实详尽的解释、具体的思考过程、理解难点解析以及更多的代码实例和应用场景介绍。
2023-02-17 18:50:30
130
雪域高原
Golang
...问,咱们通常就是扯到SQL查询啊,还有怎么管事务,再有就是怎么用连接池这些事儿。 1.1 连接池的重要性 连接池是数据库访问中非常关键的一环。它允许我们在不频繁建立新连接的情况下,重用已有的数据库连接,从而提高效率并减少资源消耗。想象一下,如果你每次执行SQL查询都要打开一个新的数据库连接,那效率该有多低啊! 1.2 SQL查询与ORM 在进行数据库操作时,我们有两种主要的方法:直接编写SQL语句或者使用ORM(对象关系映射)。直接编写SQL语句虽然能够提供更多的控制权,但可能会增加出错的风险。而ORM则通过将数据库表映射到程序中的对象,使得数据操作更加直观。不过,选择哪种方式,还要根据具体的应用场景和个人偏好来决定。 2. 实践篇 构建高性能数据库访问 现在,让我们进入实践部分。咱们这就来点儿实战教学,用几个小例子带你看看怎么用Go语言搞定又快又稳的数据库操作。 2.1 使用标准库 database/sql Go语言的标准库提供了database/sql包,它是一个用于SQL数据库的通用接口。下面是一个简单的例子: go package main import ( "database/sql" _ "github.com/go-sql-driver/mysql" // 注意这里需要导入MySQL驱动 "fmt" ) func main() { db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname") if err != nil { panic(err.Error()) } defer db.Close() // 执行一个简单的查询 rows, err := db.Query("SELECT id, name FROM users") if err != nil { panic(err.Error()) } defer rows.Close() for rows.Next() { var id int var name string err = rows.Scan(&id, &name) if err != nil { panic(err.Error()) } fmt.Println(id, name) } } 2.2 使用ORM工具:Gorm 对于更复杂的项目,使用ORM工具如Gorm可以极大地简化数据库操作。Gorm就像是给数据库操作加了个“翻译”,让我们可以用更贴近日常说话的方式来摆弄数据库里的数据,感觉就像是在玩弄对象一样轻松。下面是如何使用Gorm的一个简单示例: go package main import ( "gorm.io/driver/mysql" "gorm.io/gorm" "log" ) type User struct { ID uint Name string } func main() { dsn := "user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { log.Fatal(err) } // 创建用户 newUser := User{Name: "John Doe"} db.Create(&newUser) // 查询用户 var user User db.First(&user, newUser.ID) log.Printf("Found user: %s\n", user.Name) } 3. 性能优化技巧 在实际开发中,除了基础的数据库操作外,我们还需要考虑如何进一步优化性能。这里有几个建议: - 索引:确保你的数据库表上有适当的索引,特别是对于那些频繁查询的字段。 - 缓存:利用缓存机制(如Redis)来存储常用的数据结果,可以显著减少数据库的负载。 - 批量操作:尽量减少与数据库的交互次数,比如批量插入或更新数据。 - 异步处理:对于耗时的操作,可以考虑使用异步处理方式,避免阻塞主线程。 4. 结语 通过以上的内容,我们大致了解了如何使用Go语言进行高性能的数据库访问和操作。当然,这只是冰山一角,真正的高手之路还很长。希望能给你带来点儿灵感,让你在Go语言的路上越走越远,越走越顺!记住,编程是一场马拉松,不是短跑,保持耐心,不断学习和尝试新的东西吧! --- 希望这篇文章能帮助你更好地理解和应用Golang在数据库访问方面的最佳实践。如果你有任何问题或想法,欢迎随时交流讨论!
2024-10-21 15:42:48
78
百转千回
Spark
... 在使用Spark SQL进行操作时,需要从外部系统读取数据。 3. 使用Spark Streaming进行实时流处理时,可能会因为无法建立与上游系统的连接而抛出此异常。 四、解决UnknownHostException的方法 那么,我们该如何优雅地处理UnknownHostException呢?以下是几种常用的方法: 方法一:增加重试次数 当遇到UnknownHostException时,我们可以选择增加重试次数。这样,如果服务器只是暂时不可用,那么程序仍有可能成功运行。下面是使用Scala编写的一个示例: scala val conf = new SparkConf().setAppName("MyApp") val sc = new SparkContext(conf) val maxRetries = 5 var retryCount = 0 while (retryCount < maxRetries) { try { // 这里是你的代码... ... break } catch { case e: UnknownHostException => if (retryCount == maxRetries - 1) { throw e } println(s"Received UnknownHostException, retrying in ${maxRetries - retryCount} seconds...") Thread.sleep(maxRetries - retryCount 1000) retryCount += 1 } } 在这个示例中,我们设置了最大重试次数为5次。每次重试之间会等待一段时间,避免过度消耗资源。 方法二:使用备用数据源 如果主数据源经常出现问题,我们可以考虑使用备用数据源。这可以保证即使主数据源不可用,我们的程序仍然能够正常运行。以下是一个简单的示例: scala val conf = new SparkConf().setAppName("MyApp") val sc = new SparkContext(conf) val master = "spark://:7077" val spark = SparkSession.builder() .appName("MyApp") .master(master) .getOrCreate() // 查询数据 val data = spark.sql("SELECT FROM my_table") // 处理数据 data.show() 在这个示例中,我们设置了两个Spark配置项:spark.master和spark.sql.warehouse.dir。这两个选项分别指定了Spark集群的Master节点和数据仓库目录。这样子做的话,我们就能保证,就算某个地方的数据出了岔子,我们的程序依旧能稳稳当当地运行下去,一点儿不受影响。 方法三:检查网络连接 最后,我们还可以尝试检查网络连接是否存在问题。比如,咱们可以试试给那个疑似出问题的服务器丢个ping包瞧瞧,看看它是不是还健在,能给出正常回应不。要是搞不定的话,可能就得瞅瞅咱们的网络配置是否出了啥问题,或者直接找IT部门的大神们求救了。 五、总结 总的来说,处理UnknownHostException的关键在于找到问题的原因并采取适当的措施。不管是多试几次,还是找个备胎数据源来顶上,都能实实在在地让咱们的程序更加稳如磐石。在使用Spark开发应用的时候,我们还能充分挖掘Spark的硬核实力,比如灵活运用SQL查询功能,实时处理数据流等招数,这都能让咱们的应用性能嗖嗖提升,更上一层楼。希望通过这篇文章,你能学到一些实用的技巧,并在未来的开发工作中游刃有余。
2024-01-09 16:02:17
136
星辰大海-t
Beego
...分布式系统中如何通过动态调整连接池大小、合理设置超时时间以及优化SQL查询等手段来解决“连接池耗尽”这一棘手问题。 此外,针对云原生环境下的数据库服务,Kubernetes社区也提出了相关的解决方案。例如,通过Horizontal Pod Autoscaler(HPA)自动扩缩数据库连接池规模,配合Service Mesh实现更细粒度的流量控制和熔断机制,从而有效避免因瞬时流量高峰导致的数据库连接资源耗尽。 综上所述,理解并妥善解决数据库连接池耗尽问题已成为现代应用开发与运维的重要课题,需要开发者紧跟业界最新动态和技术发展趋势,灵活运用多种策略进行综合优化。
2023-08-08 14:54:48
553
蝶舞花间-t
转载文章
...删除相应内容。 mysqldump 导出要用到MySQL的mysqldump工具,基本用法是: shell> mysqldump [OPTIONS] database [tables] 如果你不给定任何表,整个数据库将被导出。 通过执行mysqldump --help,你能得到你mysqldump的版本支持的选项表。 注意,如果你运行mysqldump没有--quick或--opt选项,mysqldump将在导出结果前装载整个结果集到内存中,如果你正在导出一个大的数据库,这将可能是一个问题。 mysqldump支持下列选项: --add-locks 在每个表导出之前增加LOCK TABLES并且之后UNLOCK TABLE。(为了使得更快地插入到MySQL)。 --add-drop-table 在每个create语句之前增加一个drop table。 --allow-keywords 允许创建是关键词的列名字。这由表名前缀于每个列名做到。 -c, --complete-insert 使用完整的insert语句(用列名字)。 -C, --compress 如果客户和服务器均支持压缩,压缩两者间所有的信息。 --delayed 用INSERT DELAYED命令插入行。 -e, --extended-insert 使用全新多行INSERT语法。(给出更紧缩并且更快的插入语句) -, --debug[=option_string] 跟踪程序的使用(为了调试)。 --help 显示一条帮助消息并且退出。 --fields-terminated-by=... --fields-enclosed-by=... --fields-optionally-enclosed-by=... --fields-escaped-by=... --fields-terminated-by=... 这些选择与-T选择一起使用,并且有相应的LOAD DATA INFILE子句相同的含义。 LOAD DATA INFILE语法。 -F, --flush-logs 在开始导出前,洗掉在MySQL服务器中的日志文件。 -f, --force, 即使我们在一个表导出期间得到一个SQL错误,继续。 -h, --host=.. 从命名的主机上的MySQL服务器导出数据。缺省主机是localhost。 -l, --lock-tables. 为开始导出锁定所有表。 -t, --no-create-info 不写入表创建信息(CREATE TABLE语句) -d, --no-data 不写入表的任何行信息。如果你只想得到一个表的结构的导出,这是很有用的! --opt 同--quick --add-drop-table --add-locks --extended-insert --lock-tables。 应该给你为读入一个MySQL服务器的尽可能最快的导出。 -pyour_pass, --password[=your_pass] 与服务器连接时使用的口令。如果你不指定“=your_pass”部分,mysqldump需要来自终端的口令。 -P port_num, --port=port_num 与一台主机连接时使用的TCP/IP端口号。(这用于连接到localhost以外的主机,因为它使用 Unix套接字。) -q, --quick 不缓冲查询,直接导出至stdout;使用mysql_use_result()做它。 -S /path/to/socket, --socket=/path/to/socket 与localhost连接时(它是缺省主机)使用的套接字文件。 -T, --tab=path-to-some-directory 对于每个给定的表,创建一个table_name.sql文件,它包含SQL CREATE 命令,和一个table_name.txt文件,它包含数据。 注意:这只有在mysqldump运行在mysqld守护进程运行的同一台机器上的时候才工作。.txt文件的格式根据--fields-xxx和--lines--xxx选项来定。 -u user_name, --user=user_name 与服务器连接时,MySQL使用的用户名。缺省值是你的Unix登录名。 -O var=option, --set-variable var=option设置一个变量的值。可能的变量被列在下面。 -v, --verbose 冗长模式。打印出程序所做的更多的信息。 -V, --version 打印版本信息并且退出。 -w, --where=@where-condition@ 只导出被选择了的记录;注意引号是强制的! "--where=user=@jimf@" "-wuserid>1" "-wuserid<1" 最常见的mysqldump使用可能制作整个数据库的一个备份: mysqldump --opt database > backup-file.sql 但是它对用来自于一个数据库的信息充实另外一个MySQL数据库也是有用的: mysqldump --opt database | mysql --host=remote-host -C database 由于mysqldump导出的是完整的SQL语句,所以用mysql客户程序很容易就能把数据导入了: shell> mysqladmin create target_db_name shell> mysql target_db_name < backup-file.sql 就是 shell> mysql 库名 < 文件名 相关标签:工具 本文原创发布php中文网,转载请注明出处,感谢您的尊重! 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_28851659/article/details/114329359。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-02-01 23:51:06
265
转载
转载文章
...cker容器运行MySQL服务后,您可能对持续优化数据库性能、安全性以及更广泛的Docker与数据库管理的实践案例感兴趣。以下为您推荐几篇时效性和针对性较强的延伸阅读材料: 1. “Docker最佳实践:在生产环境中高效部署和管理MySQL”(TechTarget,2023年4月)——该文章详述了在实际生产环境中运用Docker部署MySQL时应遵循的最佳实践,包括资源限制、日志管理和备份恢复策略。 2. “容器化时代下MySQL安全配置的关键要点”(InfoQ,2023年5月)——探讨了在使用Docker运行MySQL时的安全风险及应对措施,例如如何加密数据传输、设置防火墙规则以保护数据库免受外部攻击。 3. “基于Kubernetes的MySQL高可用架构设计与实战”(云栖社区,2023年3月)——针对在 Kubernetes 集群中部署MySQL并实现高可用性的最新实践分享,展示了如何利用StatefulSet等特性确保数据库服务的稳定性和容灾能力。 4. “深度解析MySQL 8.0新特性及其在Docker环境中的应用”(DBAZone,2023年2月)——这篇技术解读详细介绍了MySQL 8.0版本的新功能,并结合Docker实例演示如何在容器环境下有效利用这些新特性来提升数据库性能和管理效率。 通过阅读以上推荐的文章,您可以进一步掌握Docker与MySQL结合的高级应用场景,并了解最新的数据库管理技术和行业动态,从而更好地服务于您的项目开发与运维工作。
2023-05-29 17:31:06
101
转载
MySQL
MySQL , MySQL是一种广泛使用、开源的关系型数据库管理系统(RDBMS),由Oracle公司开发并维护。在本文的上下文中,MySQL提供了一种结构化存储和管理数据的方式,通过SQL语言支持对数据进行增删改查等操作。在互联网应用、企业系统以及云计算、大数据环境下,MySQL因其稳定、高效和易于扩展的特性而得到广泛应用。 JDBC(Java Database Connectivity) , JDBC是Java编程语言中用于实现与各种关系型数据库交互的一套API标准,它允许Java程序访问和处理任何类型的数据库系统。在文章中提到的Java读取MySQL示例中,开发者正是通过导入java.sql.包并利用JDBC API来建立到MySQL数据库的连接,执行SQL语句,并获取查询结果。 缓存技术 , 缓存技术是一种提升数据读取速度的方法,通常用于减少数据库负载并提高应用程序性能。例如,Memcached和Redis就是两种常用的内存键值存储系统,可作为数据库前级缓存使用。当应用程序需要频繁读取的数据时,可以从高速缓存而非数据库直接获取,从而避免了每次请求都直接访问数据库带来的延迟。在本文中,为了提高MySQL读取效率,作者建议可以引入缓存技术以加速数据访问过程。
2024-02-28 15:31:14
130
逻辑鬼才
Datax
...们有一个订单表,包含字段id, name, amount, status等,我们想要找出所有状态为"已完成"的订单。 1. 首先,我们在配置文件中添加以下内容 2. 在上述配置文件中,我们首先定义了一个源通道(in_channel)和目标通道(out_channel)。源通道通过SQL查询获取所有的订单,然后目标通道通过IF判断语句筛选出状态为"已完成"的订单,并将其插入到新的表filtered_orders中。 五、总结 以上就是在Datax中实现数据过滤处理的一个简单例子。瞧瞧这个例子,咱们就能明白,在Datax这玩意儿里头,咱能够超级轻松地用IF判断语句给数据做个筛选处理,简直不要太方便!如果你也想在你的项目中实现数据过滤处理,不妨试试看Datax吧!
2023-01-03 10:03:02
435
灵动之光-t
转载文章
在深入理解了如何通过SQLPlus进行查询结果的个性化显示以及利用glogin.sql文件实现永久环境变量设置后,进一步探究数据库管理与优化的话题显得尤为关键。近日,Oracle发布了19c新版本,其中对SQLPlus客户端工具进行了多项改进和增强,不仅提升了性能,还提供了更为灵活的输出定制选项。例如,新增的命令行参数可以直接在启动时指定pagesize和linesize,使得用户无需登录后手动调整。 此外,针对数据库运维人员可能面临的复杂查询优化场景,一篇名为《深度解读:SQLPlus中的高效查询输出与交互式分析》的技术文章详尽探讨了如何结合现代数据可视化工具,如Tableau、Power BI等,将SQLPlus查询结果进行二次处理和展示,以更直观的方式辅助决策分析。 同时,数据库安全方面也日益受到重视,《Oracle SQLPlus权限管理及安全最佳实践》一文中,作者从实战角度出发,详解了如何在glogin.sql中嵌入权限检查脚本,确保不同角色用户登录SQLPlus时只能访问授权范围内的数据,并强调了提示符个性化设置在防止误操作和提升安全性方面的重要性。 综上所述,在实际运用SQLPlus进行数据库管理的过程中,持续关注最新技术动态、深入研究查询优化策略以及强化安全管理意识,是每位数据库管理人员不断提升自身专业素养的重要途径。
2023-07-30 12:31:19
303
转载
Go-Spring
...syntax in SQL query”(SQL查询语句无效语法)是开发者们经常遭遇的一个痛点。它如同一个突如其来的路障,阻断了我们顺利获取数据的道路。今天,咱们要一起撸起袖子,深入地把这个难题给掰扯清楚。咱会手把手地带你瞧实例代码,掰开揉碎了详细解读,共同研究怎么在Go-Spring这个环境下,巧妙又高效地避开和解决SQL查询语法出错的那些小妖精。 2. Go-Spring与SQL交互 Go-Spring集成了对数据库的良好支持,能够方便地执行SQL查询。例如,我们可以利用GORM作为ORM工具,嵌入到Go-Spring项目中,实现与数据库的交互: go import ( "github.com/go-spring/spring-boot/gorm" ) type User struct { gorm.Model Username string Password string } func main() { db := gorm.Get("default") user := User{Username: "test", Password: "password"} db.Create(&user) // 此处假设数据库表结构正确,若SQL语法有误,将抛出Invalid syntax错误 } 3. SQL查询中的常见无效语法问题及其解决方案 3.1 单引号未正确闭合 在编写包含字符串的SQL查询时,单引号是非常容易出错的地方。比如: sql SELECT FROM users WHERE username = 'test; 上述SQL语句中,由于单引号未闭合,因此会引发"Invalid syntax"错误。修正后的版本应为: sql SELECT FROM users WHERE username = 'test'; 3.2 缺少必要的关键字或运算符 假设我们在Go-Spring中构建如下查询: go db.Where("username = test").Find(&users) 这段代码会导致SQL语法错误,因为我们在比较字符串时没有使用等号两侧的引号。正确的写法应该是: go db.Where("username = ?", "test").Find(&users) 4. Go-Spring中调试和预防SQL无效语法的方法 4.1 使用预编译SQL Go-Spring通过其集成的ORM库如GORM,可以支持预编译SQL,从而减少因语法错误导致的问题。例如: go stmt := db.Statement.Create.Table("users").Where("username = ?", "test") db.Exec(stmt.SQL, stmt.Vars...) 4.2 日志记录与审查 开启Go-Spring的SQL日志记录功能,可以帮助我们实时查看实际执行的SQL语句,及时发现并纠正语法错误。 5. 结语 面对“Invalid syntax in SQL query”这个看似棘手的问题,理解其背后的原因并掌握相应的排查技巧至关重要。在使用Go-Spring这个框架时,配上一把锋利的ORM工具,再加上咱们滴严谨编程习惯,完全可以轻松把这类问题扼杀在摇篮里,让咱对数据库的操作溜得飞起,效率蹭蹭上涨!下次再遇到此类问题时,希望你能快速定位,从容应对,就如同解开一道有趣的谜题般充满成就感!
2023-07-20 11:25:54
454
时光倒流
Go-Spring
...ction() (sql.DB, error) { // 获取数据库连接的具体逻辑 } // 在Go-Spring的配置文件中注册DataSource Bean @Configuration func Config Beans(ctx ApplicationContext) { dataSource := &MyDataSource{/ 初始化参数 /} ctx.Bean("dataSource", dataSource) } // 在需要使用DataSource的Service或Repository中注入 @Service type MyService struct { dataSource DataSource autowired:"dataSource" // 其他业务方法... } 5. 小结与思考 尽管Go-Spring并没有直接复刻Java Spring中的JNDI机制,但其依赖注入的理念让我们能够以一种更符合Go语言习惯的方式来管理和组织资源,比如这里的DataSource。当你遇到“无法从JNDI资源里获取DataSource”这类棘手问题时,咱可以换个聪明的方式来解决。首先,我们可以精心设计一个合理的Bean架构,然后巧妙地运用Go-Spring的依赖注入功能。这样一来,就不用再按照传统的老套路去JNDI里苦苦查找了,而且你会发现,这样做不仅同样能达到目的,甚至还能收获更优的效果,简直是一举两得的妙招儿! 在整个解决问题的过程中,我们可以看到Go-Spring对原始Spring框架理念的传承,同时也体现了Go语言简洁、高效的特性。这其实也像是在告诉我们,在实际开发工作中,就像打游戏那样,得瞅准了技术环境的“地形地貌”,灵活切换战术,把咱们精心挑选的技术栈当作趁手的武器,最大限度地发挥它的威力,实实在在地去攻克那些棘手的问题。
2023-11-21 21:42:32
503
冬日暖阳
Hibernate
...ernate如何处理SQL方言之后,我们可以进一步探索ORM框架与数据库交互优化的前沿动态。近期,Hibernate 6.0版本已发布,其中对SQL方言的支持更加丰富和完善,引入了更多数据库特性的支持,如对时下流行的NoSQL数据库以及云数据库服务的兼容性增强,使得开发者能够更便捷地在不同数据库环境中迁移和部署应用。 同时,随着微服务架构和容器化技术的发展,数据库分片、读写分离等分布式场景日益普遍,Hibernate团队正积极研究如何通过SQL方言机制更好地支持此类复杂环境下的查询优化与执行策略。例如,结合JPA规范,Hibernate提供了新的API以支持多数据源和分页查询在分布式数据库中的无缝集成。 此外,对于特定数据库性能调优,开发者可以关注各数据库厂商推出的最新功能,并结合Hibernate SQL方言进行深度定制。例如,PostgreSQL 14中新增的物化视图特性,可通过Hibernate方言实现更高效的批量数据加载和查询响应。 综上所述,在实际项目开发中,紧跟Hibernate框架更新与数据库技术发展,深入理解和灵活运用SQL方言机制,将有助于提升系统性能,降低维护成本,并确保应用在不断变化的技术环境中保持良好适应性和扩展性。
2023-12-01 18:18:30
613
春暖花开
转载文章
SqlCommand , SqlCommand是.NET框架中System.Data.SqlClient命名空间下的一种类,用于在SQL Server数据库上执行Transact-SQL语句或存储过程。在文章中,SqlCommand对象被用来执行SQL查询命令以获取投票结果和总票数,它是连接应用程序与数据库进行数据交互的关键组件。 SqlDataReader , SqlDataReader是.NET Framework中的一个数据读取器类,位于System.Data.SqlClient命名空间下。它提供了一种只进、只读、高效的方式从SQL Server数据库检索大量记录。在文中,DataReader对象dr用于存储从数据库查询得到的各项投票结果数据,并通过Read方法逐条读取这些记录,以便进一步计算和展示投票进度。 ADO.NET , ADO(ActiveX Data Objects)的.NET版本,是一种数据访问技术,允许.NET应用程序连接到各种不同类型的数据源(如SQL Server、Oracle等),并进行数据的检索、更新、插入和删除操作。在该文上下文中,作者使用了ADO.NET的组件如SqlCommand和SqlDataReader来实现与数据库的交互,从而获取投票信息并动态生成投票进度条。 TF-IDF , TF-IDF(Term Frequency-Inverse Document Frequency)是一种广泛应用于信息检索和文本挖掘领域的统计方法,用于评估一个词对于一个文档或者一个文档集合中的重要程度。在本文中,虽然并未直接应用TF-IDF算法,但提及它的原理,即计算单项票数占总票数的比例类似于TF-IDF计算某个词汇在文档中相对重要性的思想,将投票比例映射为进度条长度。 进度条(Progress Bar) , 在用户界面设计中,进度条是一种常见的可视化组件,用于显示任务完成的程度或过程。在文中,作者通过编程方式动态调整图片宽度模拟实现了四个项目的投票进度条,直观地展示了各选项得票情况相对于总票数的百分比。
2023-09-23 15:54:07
347
转载
Scala
...,使得开发者可以使用SQL-like语法进行复杂的数据操作。近期一篇关于“Scala Implicit Conversions in Apache Spark: A Deep Dive”(《Apache Spark中Scala隐式转换的深度探究》)的技术文章就详细解析了这一特性如何提升API易用性和降低学习曲线。 同时,社区内对于隐式转换的讨论也从未停止,一方面肯定其为提高代码简洁性和一致性带来的益处,另一方面也关注其可能引发的潜在问题,如编译时难以追踪的错误源、过度使用导致的可读性下降等。因此,许多开发团队正在积极制定编码规范,以指导更合理的使用隐式转换。 此外,Scala 3(Dotty项目)在设计上对隐式查找规则进行了优化和完善,旨在解决旧版本中存在的部分问题,使隐式转换更加可控且易于理解和调试。这意味着 Scala 开发者在未来将能更好地利用隐式转换这一特性,兼顾代码优雅与工程实践。 总之,作为Scala语言的一个重要特性,隐式转换在与时俱进的同时,也需要开发者不断跟进最新的理论研究与实践动态,以便在日常开发工作中更加得心应手地运用这一功能强大的工具。
2023-12-20 23:23:54
69
凌波微步-t
Greenplum
...种基于PostgreSQL开源数据库构建的并行、分布式的大型数据存储与分析系统。在本文的语境中,它被用于处理大数据环境下的大规模关系型数据查询与分析任务。由于其高度可扩展性,Greenplum能够通过在多台机器上分布式存储和并行处理数据,有效应对海量数据处理需求。 数据文件完整性检查 , 在数据库管理中,数据文件完整性检查是一项确保数据正确无误的重要措施。文中提到的数据文件完整性校验失败,指的是在Greenplum数据库中进行数据完整性验证时,发现数据文件的内容与预期不符或者存在缺失、损坏等情况,这可能影响到数据查询的准确性以及业务系统的正常运行。 pg_dumpall , pg_dumpall是PostgreSQL(包括Greenplum)数据库自带的一种用于备份整个数据库集群的实用工具。在文章给出的例子中,pg_dumpall > backup.sql命令将所有数据库定义和数据导出为一个SQL脚本文件(backup.sql),这样可以在数据文件完整性出现问题时,利用此备份文件恢复数据库至一个已知完好的状态,确保数据的一致性和可用性。
2023-12-13 10:06:36
529
风中飘零-t
Spark
...m pyspark.sql import SparkSession spark = SparkSession.builder.appName("Structured Streaming").getOrCreate() data_stream = spark \ .readStream \ .format("kafka") \ .option("kafka.bootstrap.servers", "localhost:9092") \ .option("subscribe", "my-topic") \ .load() \ .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)") query = data_stream \ .writeStream \ .format("console") \ .outputMode("append") \ .start() query.awaitTermination() 在这个示例中,我们从 kafka 主题读取数据,并设置 watermark 为 1 分钟。这就意味着,如果我们超过一分钟没收到任何新消息,那我们就会觉得这个topic已经没啥动静了,到那时咱就可以结束查询啦。 四、 结论 在 Spark Structured Streaming 中, Processing Time 和 Event Time 是两种不同的时间概念,它们分别适用于处理实时数据和处理延迟数据。理解这两种时间概念以及如何在实际场景中使用它们是非常重要的。希望这篇文章能够帮助你更好地理解和使用 Spark Structured Streaming。
2023-11-30 14:06:21
106
夜色朦胧-t
Apache Pig
...域中的强大工具,以其SQL-like的脚本语言Pig Latin和高效的分布式计算能力深受广大开发者喜爱。在处理海量数据的时候,咱们如果巧妙地把数据切分成小块并进行压缩,这可不止是能帮我们节省存储空间那么简单,更重要的是,它能够在很大程度上让数据处理速度嗖嗖地提升上去。本文将带你一起探索如何在Apache Pig中运用这些策略,以显著提升我们的数据处理效率。 1. 数据分片 划分并行处理单元 在Apache Pig中,我们可以通过使用SPLIT语句对数据进行逻辑上的分割,从而创建多个数据流,并行进行处理。这种方式可以充分利用集群资源,大大提升任务执行效率。 pig -- 假设我们有一个名为input_data的数据集 data = LOAD 'input_data' AS (id:int, data:chararray); -- 使用SPLIT语句根据某个字段(如id)的值将数据划分为两个部分 SPLIT data INTO data_small IF id < 1000, data_large IF id >= 1000; -- 对每个分片进行独立的后续处理 small_processed = FOREACH data_small GENERATE ..., ...; large_processed = FOREACH data_large GENERATE ..., ...; 这里通过SPLIT实现了数据集的逻辑分片,根据id字段的不同范围生成了两个独立的数据流。这样,针对不同大小或性质的数据块儿,我们就可以灵活应变,采取不同的处理方法,把并行计算的威力发挥到极致,充分榨取它的潜能。 2. 数据压缩 减少存储成本与I/O开销 Apache Pig支持多种数据压缩格式,如gzip、bz2等,这不仅能有效降低存储成本,还能减少数据在网络传输和磁盘I/O过程中的时间消耗。在加载和存储数据时,我们可以通过指定合适的压缩选项来启用压缩功能。 pig -- 加载已压缩的gzipped文件 compressed_input = LOAD 'compressed_data.gz' USING PigStorage(',') AS (field1:chararray, field2:int); -- 处理数据... processed_data = FOREACH compressed_input GENERATE ..., ...; -- 存储处理结果为bz2压缩格式 STORE processed_data INTO 'output_data.bz2' USING PigStorage(',') PIGSTORAGE_COMPRESS '-bz2'; 在这段代码中,我们首先加载了一个gzip压缩格式的输入文件,并进行了相应的处理。然后呢,在存储处理完的数据时,我特意选了bz2压缩格式,这样一来,就能大大减少输出数据所需的存储空间,同时也能降低之后再次读取数据的成本,让事情变得更高效、更省事儿。 3. 深入探讨 权衡分片与压缩的影响 虽然分片和压缩都能显著提升数据处理效率,但同时也需要注意它们可能带来的额外开销。比如说,如果分片分得太细了,就可能会生出一大堆map任务,这就好比本来只需要安排一个小分队去完成的工作,结果你硬是分成了几十个小队,这样一来,调度工作量可就蹭蹭往上涨了。再来说说压缩这事,要是压得过狠,解压的时候就得花更多的时间,这就像是你为了节省打包行李的空间,把东西塞得死紧,结果到了目的地,光是打开行李找东西就花了大半天,反而浪费了不少时间,这就抵消了一部分通过压缩原本想省下的I/O时间。所以在实际用起来的时候,咱们得瞅准数据的脾性和集群环境的实际情况,灵活机动地调整分片策略和压缩等级,这样才能让性能达到最佳状态,平衡稳定。 总的来说,Apache Pig为我们提供了丰富的手段去应对大数据处理中的挑战,通过合理的分片和压缩策略,我们可以进一步挖掘其潜力,提升数据处理的效率。在这个过程中,对于我们这些开发者来说,就得像个探险家一样,不断去尝试、动手实践,还要持续优化调整,才能真正摸透Apache Pig那个家伙的厉害之处,体验到它的迷人魅力。
2023-12-10 16:07:09
459
昨夜星辰昨夜风
Hive
...Hive中“无法解析SQL查询”问题的根源与解决方案后,我们可以进一步关注Hive及其相关技术的最新发展动态和最佳实践。近期,随着大数据分析需求的增长,开源社区对Hive的优化工作从未停止。 一方面,Apache Hive 3.x版本引入了一系列新特性以增强SQL兼容性和查询性能,如对窗口函数、CTE(公共表表达式)等更复杂查询结构的支持更加完善,大大降低了用户因语法不兼容导致的“无法解析SQL查询”问题。此外,Hive LLAP(Live Long and Process)服务的改进显著提升了交互式查询响应速度,对于数据分析师而言,这意味着能够更快地获取到所需的数据洞察。 另一方面,结合最新的云原生技术和容器化部署方案,例如通过Kubernetes对Hive进行集群管理,不仅简化了运维流程,而且可以实现资源的弹性伸缩,从而有效应对大规模数据处理场景下的各类挑战。 同时,为了进一步提升查询效率,业界也在积极探索将Hive与其他大数据处理框架如Spark、Flink等深度整合,通过优化查询引擎、利用列存格式等方式,实现在保证SQL兼容性的同时,大幅提升海量数据处理能力。 综上所述,紧跟Apache Hive的发展步伐,了解并掌握其新特性和最佳实践,是解决“无法解析SQL查询”等问题,并在实际工作中高效利用Hive处理海量数据的关键所在。不断学习和实践,方能在大数据江湖中游刃有余,从容应对各种挑战。
2023-06-17 13:08:12
589
山涧溪流-t
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
id -g username
- 获取用户的GID(组ID)。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"