C# 运行时动态对象创建和动态方法调用- Joly-Han - 博客园

mikel阅读(763)

来源: C# 运行时动态对象创建和动态方法调用 – Joly-Han – 博客园

C# 运行时动态对象创建       
   运行时动态对象创建(我也不知道该叫什么名字,就姑且这么随便称呼了)确实很势大,应该是很有威力的。程序员,贴代码最直接了:

                   int n = System.Activator.CreateInstance<int>();

        这一句没啥可说的,根据类别创建对象。这里要注意的是int型别是编译时可确定的。不是typeof(int)类型。

                   Type type = Type.GetType(“System.Int32”, false, true);

                   object o = System.Activator.CreateInstance(type);

                   Debug.Assert(o.GetType() == typeof(int));

第一句是根据类型名称得到类型Type。对于工厂模式有印象的同学肯定知道该特性是多么有用。注意这里类型名称不能用int,而必须是类型的全写,int之类是C#编译器的关键字,而不是CLR的。

       第二句是根据Type生成对象。这对于有运行时动态生成对象需求的系统非常有用。不过这里的object o声明不能高级到哪去,至多你后面加一个as IYourInterface,不过还是无法在编译代码里直接描述对象类别。

                   Type type = typeof(int);

                   Type listType = typeof(List<>);

                   Type[] typeArgs = { type };

                   Type genericType = listType.MakeGenericType(typeArgs);

                   object o = Activator.CreateInstance(genericType);

                   Debug.Assert(o.GetType() == typeof(List<int>));

       这段代码更奇特了,可以动态的生成泛型对象。如果你只有在运行时才知道泛型容器的类型参数,问题该如何描述呢?上面的解决方案非常直爽,要的就是这感觉。

  

C#动态方法调用

     /// <summary>

     /// 该类将被独立编入Class1.dll汇编

     /// </summary>

     class Class1

     {

         public static string method1()

         {

              return “I am Static method (method1) in class1”;

         }

         public string method2()

         {

              return “I am a Instance Method (method2) in Class1”;

         }

         public string method3(string s)

         {

              return “Hello ” + s;

         }

     }

 

     /// <summary>

     /// 该类独立放入Test.exe汇编

     /// </summary>

     class DynamicInvoke

     {

         public static void Main(string[] args)

         {

              // 动态加载汇编

              string path = “Class1.dll”;

              Assembly assembly = Assembly.Load(path);

 

              // 根据类型名得到Type

              Type type = assembly.GetType(“Class1”);

 

              // 根据方法名动态调用静态方法

              string str = (string)type.InvokeMember(“method1”, BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[] { });

              Console.WriteLine(str);

 

              // 根据类型动态创建对象

              object o = Activator.CreateInstance(type);

 

              // 根据方法名动态调用动态对象的成员方法

              str = (string)type.InvokeMember(“method2”, BindingFlags.Default | BindingFlags.InvokeMethod, null, o, new object[] { });

              Console.WriteLine(str);

 

              // 根据方法名动态调用动态对象的有参成员方法

              object[] par = new object[] { “kunal” };

              str = (string)type.InvokeMember(“method3”, BindingFlags.Default | BindingFlags.InvokeMethod, null, o, par);

              Console.WriteLine(str);

 

              // 带out修饰的InvokeMember

              // System.Int32 中 public static bool TryParse(string s, out int result) 方法的调用

              var arguments = new object[] { str, null}; // 注意这里只能将参数写在外面,out参数为null也没有关系

              typeof(int).InvokeMember(“TryParse”, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod |System.Reflection.BindingFlags.Static,

                   null, null, arguments);

              Console.WriteLine(arguments[1]);

         }

     }

 

 

(原文地址:http://blog.sina.com.cn/dekun1002 )s

c# 匿名对象增加动态属性 - 金钱 - 博客园

mikel阅读(1178)

来源: c# 匿名对象增加动态属性 – 金钱 – 博客园

在开发过程中碰到了一个需求,需要动态创建对象及其动态属性。在尝试几种方法后,最后完成了需求,记录下过程,给园友参考下

1.动态创建对象一:匿名对象

object obj1 = new {Name = "金朝钱",Age="31",Birthday =DateTime.Now};

创建的匿名对象:

问题1:无法动态映射对象属性

解决:使用反射的方式获取对象值

object obj1 = new {Name = "金朝钱",Age="31",Birthday =DateTime.Now};
Response.Write(string.Format("Name:{0}", obj1.GetType().GetProperty("Name").GetValue(obj1, null).ToString()));

输出结果

问题2:无法动态创建对象属性

 

2.使用动态对象创建方法二、动态对象

dynamic obj2 = new System.Dynamic.ExpandoObject();
obj2.Name = "金朝钱";
obj2.Age = 31;
obj2.Birthday = DateTime.Now;
Response.Write(string.Format("Name:{0}", obj2.Name));

创建的动态对象:

输出结果:

问题:还是不能动态增加对象

 

3.动态创建对象及其属性

查看ExpandoObject的定义,发现其实质是一个Dictionary存放键值对,是否可以通过该方法来动态处理对象属性呢?

 

复制代码
Dictionary<string, object> temp = new Dictionary<string, object>();
temp.Add("Name", "金朝钱");
temp["Age"] = 31;
temp["Birthday"] = DateTime.Now;

dynamic obj = new System.Dynamic.ExpandoObject();

foreach (KeyValuePair<string, object> item in temp)
{
((IDictionary<string, object>)obj).Add(item.Key, item.Value);
}

Response.Write(string.Format("Name:{0}", obj.GetType().GetProperty("name").GetValue(obj, null).ToString()));
复制代码

 

对象查看:

输出:

输出是发生错误,不能用反射获取对象属性,经查,该对象的Field和Property全部都是null,那么我们和上面一样使用Dictionary进行输出

 

终于搞定收工,有类似需要的朋友可以参考下。

C# DynamicObject 动态对象 - MingsonZheng - 博客园

mikel阅读(1088)

来源: C# DynamicObject 动态对象 – MingsonZheng – 博客园

dynamic是FrameWork4.0的新特性。dynamic的出现让C#具有了弱语言类型的特性。编译器在编译的时候不再对类型进行检查,编译期默认dynamic对象支持你想要的任何特性。比如,即使你对GetDynamicObject方法返回的对象一无所知,你也可以像如下那样进行代码的调用,编译器不会报错:

dynamic dynamicObject = GetDynamicObject();
Console.WriteLine(dynamicObject.Name);
Console.WriteLine(dynamicObject.SampleMethod());

dynamic与var关键字本质区别

var只能用作局部变量,不能用于字段,参数;声明的同时必须初始化;初始化时类型就已经确定了,并且不能再被赋值不能进行隐式类型转换的类型的数据。

var实际上是编译期抛给我们的“语法糖”,一旦被编译,编译期会自动匹配var 变量的实际类型,并用实际类型来替换该变量的申明,这看上去就好像我们在编码的时候是用实际类型进行申明的。

dynamic可用于类型的字段,方法参数,方法返回值,可用于泛型的类型参数等;可以赋值给或被赋值任何类型并且不需要显式的强制类型转换,因为这些是运行时执行的,这要得益于dynamic类型的动态特性。

dynamic被编译后,实际是一个object类型,只不过编译器会对dynamic类型进行特殊处理,让它在编译期间不进行任何的类型检查,而是将类型检查放到了运行期。

从visual studio的编辑器窗口就能看出来。以var声明的变量,支持“智能感知”,因为visual studion能推断出var类型的实际类型,而以dynamic声明的变量却不支持“智能感知”,因为编译器对其运行期的类型一无所知。对dynamic变量使用“智能感知”,会提示“此操作将在运行时解析”。

类型转换

Dynamic类型的实例和其他类型的实例间的转换是很简单的,开发人员能够很方便地在dyanmic和非dynamic行为间切换。任何实例都能隐式转换为dynamic类型实例,见下面的例子:

dynamic d1 = 7;
dynamic d2 = "a string";
dynamic d3 = System.DateTime.Today;
dynamic d4 = System.Diagnostics.Process.GetProcesses();

Conversely, an implicit conversion can be dynamically applied to any expression of type dynamic.
反之亦然,类型为dynamic的任何表达式也能够隐式转换为其他类型。

int i = d1;
string str = d2;
DateTime dt = d3;
System.Diagnostics.Process[] procs = d4;

方法中含有dynamic类型参数的重载问题

如果调用一个方法是传递了dynamic类型的对象,或者被调用的对象是dynamic类型的,那么重载的判断是发生在运行时而不是编译时。
动态语言运行时(dynamic language runtime DLR)动态语言运行时是.NET Framework 4 Beta 1中的一组新的API,它提供了对C#中dynamic类型的支持,也实现了像IronPython和IronRuby之类的动态程序设计语言。

dynamic 简化反射

以前我们这样使用反射:

public class DynamicSample
{
public string Name { get; set; }

public int Add(int a, int b)
{
return a + b;
}
}
DynamicSample dynamicSample = new DynamicSample(); //create instance为了简化演示,我没有使用反射
var addMethod = typeof(DynamicSample).GetMethod("Add");
int re = (int)addMethod.Invoke(dynamicSample, new object[] { 1, 2 });

现在,我们有了简化的写法:

dynamic dynamicSample2 = new DynamicSample();
int re2 = dynamicSample2.Add(1, 2);

var,dynamic,传统确定类型的效率对比

传统类型的效率 >= var动态类型 > dynamic动态类型

编译器对dynamic进行了优化,比没有经过缓存的反射效率高。

参考文章:

https://www.cnblogs.com/qiuweiguo/archive/2011/08/03/2125982.html
https://blog.csdn.net/shanyongxu/article/details/47296033

layui的table单击行勾选checkbox功能方法_javascript技巧_脚本之家

mikel阅读(1140)

来源: layui的table单击行勾选checkbox功能方法_javascript技巧_脚本之家

实现原理:找到table的div绑定单击事件到表格的行:

1、取得行的索引data-index,为后面查找checkbox的控件作准备

2、根据是否有固定列查找checkbox所在的表格table(当存在固定列时,固定列是另一个table,checkbox控件就在这上面,因此要优先取这个)

3、通过table和data-index查找checkbox控件”td div.laytable-cell-checkbox div.layui-form-checkbox I”,如果存在,则执行单击

4、对td的单击事件进行拦截停止,防止事件冒泡再次触发上述的单击事件5、将此代码在页面初始化后执行一次即可以。

实现效果:单击行,自动选中或取消勾选。

以上这篇layui的table单击行勾选checkbox功能方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

//单击行勾选checkbox事件
$(document).on(“click”,”.layui-table-body table.layui-table tbody tr”, function () {
var index = $(this).attr(‘data-index’);
var tableBox = $(this).parents(‘.layui-table-box’);
//存在固定列
if (tableBox.find(“.layui-table-fixed.layui-table-fixed-l”).length>0) {
tableDiv = tableBox.find(“.layui-table-fixed.layui-table-fixed-l”);
} else {
tableDiv = tableBox.find(“.layui-table-body.layui-table-main”);
}
var checkCell = tableDiv.find(“tr[data-index=” + index + “]”).find(“td div.laytable-cell-checkbox div.layui-form-checkbox I”);
if (checkCell.length>0) {
checkCell.click();
}
});

$(document).on(“click”, “td div.laytable-cell-checkbox div.layui-form-checkbox”, function (e) {
e.stopPropagation();
});

C#开发:openfiledialog的使用 - 希格绍尔 - 博客园

mikel阅读(911)

来源: C#开发:openfiledialog的使用 – 希格绍尔 – 博客园

C#开发:openfiledialog的使用
文件对话框(FileDialog)

一、打开文件对话框(OpenFileDialog)

1、 OpenFileDialog控件有以下基本属性

InitialDirectory 对话框的初始目录
Filter 要在对话框中显示的文件筛选器,例如,”文本文件(*.txt)|*.txt|所有文件(*.*)||*.*”
FilterIndex 在对话框中选择的文件筛选器的索引,如果选第一项就设为1
RestoreDirectory 控制对话框在关闭之前是否恢复当前目录
FileName 第一个在对话框中显示的文件或最后一个选取的文件
Title 将显示在对话框标题栏中的字符
AddExtension 是否自动添加默认扩展名
CheckPathExists
在对话框返回之前,检查指定路径是否存在
DefaultExt 默认扩展名
DereferenceLinks 在从对话框返回前是否取消引用快捷方式
ShowHelp
启用”帮助”按钮
ValiDateNames 控制对话框检查文件名中是否不含有无效的字符或序列

2、 OpenFileDialog控件有以下常用事件

FileOk 当用户点击”打开”或”保存”按钮时要处理的事件
HelpRequest 当用户点击”帮助”按钮时要处理的事件

 

可以用以下代码来实现上面这个对话框:

private void openFileDialogBTN_Click(object sender, System.EventArgs e){
OpenFileDialog openFileDialog=new OpenFileDialog();
openFileDialog.InitialDirectory=”c:\\”;//注意这里写路径时要用c:\\而不是c:\
openFileDialog.Filter=”文本文件|*.*|C#文件|*.cs|所有文件|*.*”;
openFileDialog.RestoreDirectory=true;
openFileDialog.FilterIndex=1;
if (openFileDialog.ShowDialog()==DialogResult.OK)
{
fName=openFileDialog.FileName;
File fileOpen=new File(fName);
isFileHaveName=true;
richTextBox1.Text=fileOpen.ReadFile();
richTextBox1.AppendText(“”);
}
}

路径的返回用filename是字符串类型

如:openFileDialog1.ShowDialog();
_name1= openFileDialog1.FileName;
Image imge = Image.FromFile(_name1);

C#自定义Attribute的定义和获取简例 - 上校 - 博客园

mikel阅读(2051)

来源: C#自定义Attribute的定义和获取简例 – 上校 – 博客园

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Reflection;

namespace WebApplication4
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
abc ta = new abc();
Type type = ta.GetType();
GetTableName(type);

PropertyInfo[] propertys = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);

foreach (PropertyInfo p in propertys)
{
//此处用了PropertyInfo.GetCustomAttributes方法,该方法继承至MemberInfo
object[] objs = p.GetCustomAttributes(false);
foreach (object obj in objs)
{
//string PK = GetPrimaryKey(obj);
string ColumnName = GetColumnName(obj);
}
}
}

public static string GetTableName(Type classType)
{
string strTableName = string.Empty;
string strEntityName = string.Empty;
string strTableTel = string.Empty;

strEntityName = classType.FullName;//类的全名

//此处用了System.Type.GetCustomAttributes 方法,该方法继承至MemberInfo object classAttr = classType.GetCustomAttributes(false)[0];
if (classAttr is TableAttribute)
{
TableAttribute tableAttr = classAttr as TableAttribute;
strTableName = tableAttr.Name;
strTableTel = tableAttr.Tel;
}
if (string.IsNullOrEmpty(strTableName))
{
throw new Exception(“实体类:” + strEntityName + “的属性配置[Table(name=\”tablename\”)]错误或未配置”);
}
if (string.IsNullOrEmpty(strTableTel))
{
throw new Exception(“实体类:” + strEntityName + “的属性配置[Table(tel=\”telname\”)]错误或未配置”);
}

return strTableName;
}

public static string GetPrimaryKey(object attribute)
{
string strPrimary = string.Empty;
IdAttribute attr = attribute as IdAttribute;
switch (attr.Strategy)
{
case GenerationType.INDENTITY:
break;
case GenerationType.SEQUENCE:
strPrimary = System.Guid.NewGuid().ToString();
break;
case GenerationType.TABLE:
break;
}

return strPrimary;
}

public static string GetColumnName(object attribute)
{
string columnName = string.Empty;
if (attribute is ColumnAttribute)
{
ColumnAttribute columnAttr = attribute as ColumnAttribute;
columnName = columnAttr.Name;
}
else if (attribute is IdAttribute)
{
IdAttribute idAttr = attribute as IdAttribute;
columnName = idAttr.Name;
}

return columnName;
}
}

[Table(Name = “Student”,Tel=”ew”)]
public class abc
{
private string _a = string.Empty;
[Id(Name = “studentid”, Strategy = GenerationType.INDENTITY)]
public string a
{
get { return _a; }
set { _a = value; }
}
private string _b = string.Empty;
[Column(Name = “studentno”)]
public string b
{
get { return _b; }
set { _b = value; }
}

public string c = string.Empty;
}

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class TableAttribute : Attribute
{
public TableAttribute() { }

private string _Name = string.Empty;
public string Name
{
get { return _Name; }
set { _Name = value; }
}

private string _Tel = string.Empty;
public string Tel
{
get { return _Tel; }
set { _Tel = value; }
}
}

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class IdAttribute : Attribute
{
private string _Name = string.Empty;
private int _Strategy = GenerationType.INDENTITY;

public string Name
{
get { return _Name; }
set { _Name = value; }
}

public int Strategy
{
get { return _Strategy; }
set { _Strategy = value; }
}
}

public class GenerationType
{
public const int INDENTITY = 1;//自动增长
public const int SEQUENCE = 2;//序列
public const int TABLE = 3;//TABLE

private GenerationType() { }//私有构造函数,不可被实例化对象
}

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = false, Inherited = false)]
public class ColumnAttribute : Attribute
{
public ColumnAttribute() { }

private string _Name = string.Empty;//列名
private bool _IsUnique = false;//是否唯一
private bool _IsNull = true;//是否允许为空
private bool _IsInsert = true;//是否插入到表中
private bool _IsUpdate = true;//是否修改到表中

public string Name
{
get { return _Name; }
set { _Name = value; }
}

public bool IsUnique
{
get { return _IsUnique; }
set { _IsUnique = value; }
}

public bool IsNull
{
get { return _IsNull; }
set { _IsNull = value; }
}

public bool IsInsert
{
get { return _IsInsert; }
set { _IsInsert = value; }
}

public bool IsUpdate
{
get { return _IsUpdate; }
set { _IsUpdate = value; }
}
}
}

C#自定义Attribute值的获取与优化 - junjieok - 博客园

mikel阅读(897)

来源: C#自定义Attribute值的获取与优化 – junjieok – 博客园

C#自定义Attribute值的获取是开发中会经常用到的,一般我们的做法也就是用反射进行获取的,代码也不是很复杂。

1、首先有如下自定义的Attribute

复制代码
 1     [AttributeUsage(AttributeTargets.All)]
 2     public sealed class NameAttribute : Attribute
 3     {
 4         private readonly string _name;
 5 
 6         public string Name
 7         {
 8             get { return _name; }
 9         }
10 
11         public NameAttribute(string name)
12         {
13             _name = name;
14         }
15     }
复制代码

2、定义一个使用NameAttribute的类

复制代码
1     [Name("dept")]
2     public class CustomAttributes
3     {
4         [Name("Deptment Name")]
5         public string Name { get; set; }
6 
7         [Name("Deptment Address")]
8         public string Address;
9     }
复制代码

3、获取CustomAttributes类上的”dept”也就很简单了

复制代码
 1         private static string GetName()
 2         {
 3             var type = typeof(CustomAttributes);
 4 
 5             var attribute = type.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault();
 6 
 7             if (attribute == null)
 8             {
 9                 return null;
10             }
11 
12             return ((NameAttribute)attribute).Name;
13         }
复制代码

以上代码就可以简单的获取,类上的Attribute的值了,但是需求往往不是这么简单的,不仅要获取类头部Attribute上的值,还要获取字段Address头部Attribute上的值。有的同学可能就觉得这还不简单呀,直接上代码

复制代码
 1         private static string GetAddress()
 2         {
 3             var type = typeof (CustomAttributes);
 4 
 5             var fieldInfo = type.GetField("Address");
 6             if (fieldInfo == null)
 7             {
 8                 return null;
 9             }
10 
11             var attribute = fieldInfo.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault();
12 
13             if (attribute == null)
14             {
15                 return null;
16             }
17 
18             return ((NameAttribute) attribute).Name;
19         }
复制代码

上面代码就是获取Address字段头部上的Attribute值了。虽然我们是获取到了我们想要的,但是我们发现这样做是不是太累了,如果又扩展一个自定义的Attribute,或者又在一个新的属性或字段上标上Attribute时,我们又要写一段代码来实现我想要的,这些严重代码违反了DRY的设计原则。我们知道获取Attribute是通过反射来取的,Attribute那个值又是不变的,这样就没必要每次都要进行反射来获取了。基于以上两点代码进行了如下的优化,优化后的代码如下:

复制代码
  1     public static class CustomAttributeHelper
  2     { 
  3         /// <summary>
  4         /// Cache Data
  5         /// </summary>
  6         private static readonly Dictionary<string, string> Cache = new Dictionary<string, string>();
  7 
  8         /// <summary>
  9         /// 获取CustomAttribute Value
 10         /// </summary>
 11         /// <typeparam name="T">Attribute的子类型</typeparam>
 12         /// <param name="sourceType">头部标有CustomAttribute类的类型</param>
 13         /// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
 14         /// <returns>返回Attribute的值,没有则返回null</returns>
 15         public static string GetCustomAttributeValue<T>(this Type sourceType, Func<T, string> attributeValueAction) where T : Attribute
 16         {
 17             return GetAttributeValue(sourceType, attributeValueAction, null);
 18         }
 19 
 20         /// <summary>
 21         /// 获取CustomAttribute Value
 22         /// </summary>
 23         /// <typeparam name="T">Attribute的子类型</typeparam>
 24         /// <param name="sourceType">头部标有CustomAttribute类的类型</param>
 25         /// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
 26         /// <param name="name">field name或property name</param>
 27         /// <returns>返回Attribute的值,没有则返回null</returns>
 28         public static string GetCustomAttributeValue<T>(this Type sourceType, Func<T, string> attributeValueAction,
 29             string name) where T : Attribute
 30         {
 31             return GetAttributeValue(sourceType, attributeValueAction, name);
 32         }
 33 
 34         private static string GetAttributeValue<T>(Type sourceType, Func<T, string> attributeValueAction,
 35             string name) where T : Attribute
 36         {
 37             var key = BuildKey(sourceType, name);
 38             if (!Cache.ContainsKey(key))
 39             {
 40                 CacheAttributeValue(sourceType, attributeValueAction, name);
 41             }
 42 
 43             return Cache[key];
 44         }
 45 
 46         /// <summary>
 47         /// 缓存Attribute Value
 48         /// </summary>
 49         private static void CacheAttributeValue<T>(Type type,
 50             Func<T, string> attributeValueAction, string name)
 51         {
 52             var key = BuildKey(type, name);
 53 
 54             var value = GetValue(type, attributeValueAction, name);
 55 
 56             lock (key + "_attributeValueLockKey")
 57             {
 58                 if (!Cache.ContainsKey(key))
 59                 {
 60                     Cache[key] = value;
 61                 }
 62             }
 63         }
 64 
 65         private static string GetValue<T>(Type type,
 66             Func<T, string> attributeValueAction, string name)
 67         {
 68             object attribute = null;
 69             if (string.IsNullOrEmpty(name))
 70             {
 71                 attribute =
 72                     type.GetCustomAttributes(typeof (T), false).FirstOrDefault();
 73             }
 74             else
 75             {
 76                 var propertyInfo = type.GetProperty(name);
 77                 if (propertyInfo != null)
 78                 {
 79                     attribute =
 80                         propertyInfo.GetCustomAttributes(typeof (T), false).FirstOrDefault();
 81                 }
 82 
 83                 var fieldInfo = type.GetField(name);
 84                 if (fieldInfo != null)
 85                 {
 86                     attribute = fieldInfo.GetCustomAttributes(typeof (T), false).FirstOrDefault();
 87                 }
 88             }
 89 
 90             return attribute == null ? null : attributeValueAction((T) attribute);
 91         }
 92 
 93         /// <summary>
 94         /// 缓存Collection Name Key
 95         /// </summary>
 96         private static string BuildKey(Type type, string name)
 97         {
 98             if (string.IsNullOrEmpty(name))
 99             {
100                 return type.FullName;
101             }
102 
103             return type.FullName + "." + name;
104         }
105     }
复制代码

以上优化后的代码:

把不同的代码用泛型T,Fun<T,stirng>来处理来减少重复的代码;
把取过的Attribute值存到一个Dictionary中,下次再来取时,如果有则直接返回Dictionary中的值,如果没有才通过反射来取相应的Attribute值,这样大大的提高效率;

调用方法也更加的简单了,代码如下:

1             var cName=typeof(CustomAttributes).GetCustomAttributeValue<NameAttribute>(x => x.Name);
2             var fName = typeof (CustomAttributes).GetCustomAttributeValue<NameAttribute>(x => x.Name, "Address");

有没有, 是不是很简单,而且调用方式对缓存是完全透明的!

大数据技术之_12_Sqoop学习_Sqoop 简介+Sqoop 原理+Sqoop 安装+Sqoop 的简单使用案例+Sqoop 一些常用命令及参数 - 黑泽君 - 博客园

mikel阅读(617)

第1章 Sqoop 简介第2章 Sqoop 原理第3章 Sqoop 安装3.1 下载并解压3.2 修改配置文件3.3 拷贝 JDBC 驱动3.4 验证 Sqoop3.5 测试 Sqoop 是否能够成功

来源: 大数据技术之_12_Sqoop学习_Sqoop 简介+Sqoop 原理+Sqoop 安装+Sqoop 的简单使用案例+Sqoop 一些常用命令及参数 – 黑泽君 – 博客园

 


第1章 Sqoop 简介第2章 Sqoop 原理第3章 Sqoop 安装3.1 下载并解压3.2 修改配置文件3.3 拷贝 JDBC 驱动3.4 验证 Sqoop3.5 测试 Sqoop 是否能够成功连接数据库第4章 Sqoop 的简单使用案例4.1 导入数据4.1.1 从 RDBMS 到 HDFS4.1.2 从 RDBMS 到 Hive4.1.3 从 RDBMS 到 HBase4.2 导出数据4.2.1 从 HIVE/HDFS 到 RDBMS4.3 脚本打包第5章 Sqoop 一些常用命令及参数5.1 常用命令列举5.2 命令&参数详解5.2.1 公用参数:数据库连接5.2.2 公用参数:import5.2.3 公用参数:export5.2.4 公用参数:hive5.2.5 命令&参数:import5.2.6 命令&参数:export5.2.7 命令&参数:codegen5.2.8 命令&参数:create-hive-table5.2.9 命令&参数:eval5.2.10 命令&参数:import-all-tables5.2.11 命令&参数:job5.2.12 命令&参数:list-databases5.2.13 命令&参数:list-tables5.2.14 命令&参数:merge5.2.15 命令&参数:metastore


第1章 Sqoop 简介

  Sqoop 是一款开源的工具,主要用于在 Hadoop(Hive) 与传统的数据库 (mySQL,postgreSQL,...) 间进行数据的高校传递,可以将一个关系型数据库(例如:MySQL,Oracle,Postgres等)中的数据导入到 Hadoop 的 HDFS 中,也可以将 HDFS 的数据导进到关系型数据库中。
Sqoop 项目开始于 2009 年,最早是作为 Hadoop 的一个第三方模块存在,后来为了让使用者能够快速部署,也为了让开发人员能够更快速的迭代开发,Sqoop 独立成为一个 Apache 顶级项目。
Sqoop2 的最新版本是 1.99.7。请注意,2 与 1 不兼容,且特征不完整,它并不打算用于生产部署。

第2章 Sqoop 原理

  将导入或导出命令翻译成 mapreduce 程序来实现。
在翻译出的 mapreduce 中主要是对 inputformat 和 outputformat 进行定制。

第3章 Sqoop 安装

  安装 Sqoop 的前提是已经具备 Java 和 Hadoop 的环境。

3.1 下载并解压

1) 下载地址:http://mirrors.hust.edu.cn/apache/sqoop/1.4.6/
2) 上传安装包 sqoop-1.4.6.bin__hadoop-2.0.4-alpha.tar.gz 到虚拟机中
3) 解压 sqoop 安装包到指定目录,如:

$ tar -zxf sqoop-1.4.6.bin__hadoop-2.0.4-alpha.tar.gz -C /opt/module/

4) 重命名 sqoop 安装目录,如:

[atguigu@hadoop102 module]$ mv sqoop-1.4.6.bin__hadoop-2.0.4-alphasqoop

3.2 修改配置文件

Sqoop 的配置文件与大多数大数据框架类似,在 sqoop 根目录下的 conf 目录中。
1) 重命名配置文件

$ mv sqoop-env-template.sh sqoop-env.sh

2) 修改配置文件

[atguigu@hadoop102 conf]$ pwd
/opt/module/sqoop/conf
[atguigu@hadoop102 conf]$ vim sqoop-env.sh

export HADOOP_COMMON_HOME=/opt/module/hadoop-2.7.2
export HADOOP_MAPRED_HOME=/opt/module/hadoop-2.7.2
export HIVE_HOME=/opt/module/hive
export ZOOKEEPER_HOME=/opt/module/zookeeper-3.4.10
export ZOOCFGDIR=/opt/module/zookeeper-3.4.10
export HBASE_HOME=/opt/module/hbase

3.3 拷贝 JDBC 驱动

拷贝 jdbc 驱动到 sqoop 的 lib 目录下,如:

[atguigu@hadoop102 sqoop]$ cp /opt/software/mysql-libs/mysql-connector-java-5.1.27/mysql-connector-java-5.1.27-bin.jar /opt/module/sqoop/lib/

3.4 验证 Sqoop

我们可以通过某一个 command 来验证 sqoop 配置是否正确:

[atguigu@hadoop102 sqoop]$ bin/sqoop help

出现一些 Warning 警告(警告信息已省略),并伴随着帮助命令的输出:

Available commands:
  codegen            Generate code to interact with database records
  create-hive-table     Import a table definition into Hive
  eval               Evaluate a SQL statement and display the results
  export             Export an HDFS directory to a database table
  help               List available commands
  import             Import a table from a database to HDFS
  import-all-tables     Import tables from a database to HDFS
  import-mainframe    Import datasets from a mainframe server to HDFS
  job                Work with saved jobs
  list-databases        List available databases on a server
  list-tables           List available tables in a database
  merge              Merge results of incremental imports
  metastore           Run a standalone Sqoop metastore
  version            Display version information

3.5 测试 Sqoop 是否能够成功连接数据库

[atguigu@hadoop102 sqoop]$ bin/sqoop list-databases --connect jdbc:mysql://hadoop102:3306/ --username root --password 123456

出现如下输出:

information_schema
metastore
mysql
performance_schema
test

第4章 Sqoop 的简单使用案例

4.1 导入数据

  在 Sqoop 中,“导入”概念指:从非大数据集群(RDBMS)向大数据集群(HDFS,HIVE,HBASE)中传输数据,叫做:导入,即使用 import 关键字。

4.1.1 从 RDBMS 到 HDFS

1) 确定 Mysql 服务开启正常
查询监控端口或者查询进程来确定,以下两种办法可以确认mysql是否在启动运行状态:
办法一:查询端口

$ netstat -tulpn

MySQL监控的是TCP的3306端口,如下图,说明MySQL服务在运行中。

办法二:查询进程

ps -ef | grep mysqld

可以看见mysql的进程

2) 在 Mysql 中新建一张表并插入一些数据

$ mysql -uroot -p123456
mysql> create database company;
mysql> create table company.staff(id int(4) primary key not null auto_increment, name varchar(255), sex varchar(255));
mysql> insert into company.staff(name, sex) values('Thomas''Male');
mysql> insert into company.staff(name, sex) values('Catalina''FeMale');

3) 导入数据
(1)全部导入

[atguigu@hadoop102 sqoop]$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--target-dir /user/company \
--delete-target-dir \
--num-mappers 1 \
--fields-terminated-by "\t"

(2)查询导入

[atguigu@hadoop102 sqoop]$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--target-dir /user/company \
--delete-target-dir \
--num-mappers 1 \
--fields-terminated-by "\t" \
--query 'select name,sex from staff where id <=1 and $CONDITIONS;'

等价于

[atguigu@hadoop102 sqoop]$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--target-dir /user/company \
--delete-target-dir \
--num-mappers 1 \
--fields-terminated-by "\t" \
--query "select name,sex from staff where id <=1 and \$CONDITIONS;"

提示:must contain ‘$CONDITIONS’ in WHERE clause.
$CONDITIONS:传递作用。
如果 query 后使用的是双引号,则 $CONDITIONS 前必须加转义符,防止 shell 识别为自己的变量。
(3)导入指定列

[atguigu@hadoop102 sqoop]$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--columns id,sex \
--target-dir /user/company \
--delete-target-dir \
--num-mappers 1 \
--fields-terminated-by "\t"

提示:columns中如果涉及到多列,用逗号分隔,分隔时不要添加空格。
(4)使用 sqoop 关键字筛选查询导入数据

[atguigu@hadoop102 sqoop]$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--where "id=1" \
--target-dir /user/company \
--delete-target-dir \
--num-mappers 1 \
--fields-terminated-by "\t"

[atguigu@hadoop102 sqoop]$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--columns id,sex \
--where "id=1" \
--target-dir /user/company \
--delete-target-dir \
--num-mappers 1 \
--fields-terminated-by "\t"

4.1.2 从 RDBMS 到 Hive

(1)全部导入

[atguigu@hadoop102 sqoop]$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--num-mappers 1 \
--fields-terminated-by "\t" \
--hive-import \
--hive-overwrite \
--hive-table staff_hive

提示:该过程分为两步,第一步将数据导入到 HDFS,第二步将导入到 HDFS 的数据迁移到 Hive 仓库,第一步默认的临时目录是 /user/atguigu/表名。

4.1.3 从 RDBMS 到 HBase

(1)导入数据

[atguigu@hadoop102 sqoop]$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--columns "id,name,sex" \
--num-mappers 1 \
--column-family "info" \
--hbase-create-table \
--hbase-row-key "id" \
--hbase-table "hbase_staff" \
--split-by id

会报错,如下图所示:

原因:sqoop1.4.6 只支持 HBase1.0.1 之前的版本的自动创建 HBase 表的功能。
解决方案:手动创建 HBase 表

hbase> create 'hbase_staff','info'

(5) 在 HBase 中 scan 这张表得到如下内容

hbase> scan ‘hbase_staff’

4.2 导出数据

在Sqoop中,“导出”概念指:从大数据集群(HDFS,HIVE,HBASE)向非大数据集群(RDBMS)中传输数据,叫做:导出,即使用 export 关键字。

4.2.1 从 HIVE/HDFS 到 RDBMS

(1)导出数据

[atguigu@hadoop102 sqoop]$ bin/sqoop export \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--num-mappers 1 \
--export-dir /user/hive/warehouse/staff_hive \
--input-fields-terminated-by "\t"

提示:Mysql 中如果表不存在,不会自动创建。

4.3 脚本打包

使用opt格式的文件打包 sqoop 命令,然后执行。
1) 创建一个 xxx.opt 文件

[atguigu@hadoop102 sqoop]$ pwd
/opt/module/sqoop
[atguigu@hadoop102 sqoop]$ mkdir opt
[atguigu@hadoop102 sqoop]$ touch opt/job_HDFS2RDBMS.opt

2) 编写 sqoop 脚本

[atguigu@hadoop102 sqoop]$ cd opt/
[atguigu@hadoop102 opt]$ vim job_HDFS2RDBMS.opt 

export
--connect
jdbc:mysql://hadoop102:3306/company
--username
root
--password
123456
--table
staff
--num-mappers
1
--export-dir
/user/hive/warehouse/staff_hive
--input-fields-terminated-by
"\t"

3) 执行该脚本

[atguigu@hadoop102 sqoop]$ bin/sqoop --options-file opt/job_HDFS2RDBMS.opt

尖叫提示:Mysql 中如果表不存在,不会自动创建,所以我们要先创建表 staff,如果表 staff 存在,我们应该清除掉 staff 表的数据,不然会出现主键冲突!如下图所示:
通过查看日志历史服务器,可知:

第5章 Sqoop 一些常用命令及参数

5.1 常用命令列举

  这里给大家列出来了一部分 Sqoop 操作时的常用参数,以供参考,需要深入学习的可以参看对应类的源代码。

如下表所示:

序号 命令 说明
1 import ImportTool 将数据导入到集群
2 export ExportTool 将集群数据导出
3 codegen CodeGenTool 获取数据库中某张表数据生成 Java 并打包 Jar
4 create-hive-table CreateHiveTableTool 创建 Hive 表
5 eval EvalSqlTool 查看 SQL 执行结果
6 import-all-tables ImportAllTablesTool 导入某个数据库下所有表到 HDFS 中
7 job JobTool 用来生成一个 sqoop 的任务,生成后,该任务并不执行,除非使用命令执行该任务。
8 list-databases ListDatabasesTool 列出所有数据库名
9 list-tables ListTablesTool 列出某个数据库下所有表
10 merge MergeTool 将 HDFS 中不同目录下面的数据合并在一起,并存放在指定的目录中
11 metastore MetastoreTool 记录 sqoop job 的元数据信息,如果不启动 metastore 实例,则默认的元数据存储目录为:~/.sqoop,如果要更改存储目录,可以在配置文件 sqoop-site.xml 中进行更改。
12 help HelpTool 打印 sqoop 帮助信息
13 version VersionTool 打印 sqoop 版本信息

5.2 命令&参数详解

  刚才列举了一些 Sqoop 的常用命令,对于不同的命令,有不同的参数,让我们来一一列举说明。
首先来我们来介绍一下公用的参数,所谓公用参数,就是大多数命令都支持的参数。

5.2.1 公用参数:数据库连接

序号 参数 说明
1 –connect 连接关系型数据库的URL
2 –connection-manager 指定要使用的连接管理类
3 –driver Hadoop 根目录
4 –help 打印帮助信息
5 –password 连接数据库的密码
6 –username 连接数据库的用户名
7 –verbose 在控制台打印出详细信息

5.2.2 公用参数:import

序号 参数 说明
1 –enclosed-by < char> 给字段值前加上指定的字符
2 –escaped-by < char> 对字段中的双引号加转义符
3 –fields-terminated-by < char> 设定每个字段是以什么符号作为结束,默认为逗号
4 –lines-terminated-by < char> 设定每行记录之间的分隔符,默认是 \n
5 –mysql-delimiters Mysql默认的分隔符设置,字段之间以逗号分隔,行之间以 \n分隔,默认转义符是 \,字段值以单引号包裹
6 –optionally-enclosed-by < char> 给带有双引号或单引号的字段值前后加上指定字符

5.2.3 公用参数:export

序号 参数 说明
1 –input-enclosed-by < char> 对字段值前后加上指定字符
2 –input-escaped-by < char> 对含有转移符的字段做转义处理
3 –input-fields-terminated-by < char> 字段之间的分隔符
4 –input-lines-terminated-by < char> 行之间的分隔符
5 –input-optionally-enclosed-by < char> 给带有双引号或单引号的字段前后加上指定字符

5.2.4 公用参数:hive

序号 参数 说明
1 –hive-delims-replacement < arg> 用自定义的字符串替换掉数据中的 \r\n 和 \013 \010 等字符
2 –hive-drop-import-delims 在导入数据到 hive 时,去掉数据中的 \r\n \013 \010这样的字符
3 –map-column-hive < arg> 生成 hive 表时,可以更改生成字段的数据类型
4 –hive-partition-key 创建分区,后面直接跟分区名,分区字段的默认类型为 string
5 –hive-partition-value < v> 导入数据时,指定某个分区的值
6 –hive-home < dir> hive 的安装目录,可以通过该参数覆盖之前默认配置的目录
7 –hive-import 将数据从关系数据库中导入到 hive 表中
8 –hive-overwrite 覆盖掉在 hive 表中已经存在的数据
9 –create-hive-table 默认是 false,即,如果目标表已经存在了,那么创建任务失败。
10 –hive-table 后面接要创建的 hive 表,默认使用 MySQL 的表名
11 –table 指定关系数据库的表名

公用参数介绍完之后,我们来按照命令介绍命令对应的特有参数。

5.2.5 命令&参数:import

将关系型数据库中的数据导入到 HDFS(包括Hive,HBase)中,如果导入的是 Hive,那么当 Hive 中没有对应表时,则自动创建。
1) 命令:
如:导入数据到 hive 中

$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--hive-import

如:增量导入数据到 hive 中,mode=append

append导入:

$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--num-mappers 1 \
--fields-terminated-by "\t" \
--target-dir /user/hive/warehouse/staff_hive \
--check-column id \
--incremental append \
--last-value 3

尖叫提示:append 不能与 –hive 等参数同时使用(Append mode for hive imports is not yet supported. Please remove the parameter –append-mode)

如:增量导入数据到 hdfs 中,mode=lastmodified

先在mysql中建表并插入几条数据:
mysql> create table company.staff_timestamp(id int(4), name varchar(255), sex varchar(255), last_modified timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);
mysql> insert into company.staff_timestamp (id, name, sex) values(1'AAA''female');
mysql> insert into company.staff_timestamp (id, name, sex) values(2'BBB''female');

先导入一部分数据:
$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff_timestamp \
--delete-target-dir \
--m 1

再增量导入一部分数据:
mysql> insert into company.staff_timestamp (id, name, sex) values(3'CCC''female');

$ bin/sqoop import \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff_timestamp \
--check-column last_modified \
--incremental lastmodified \
--last-value "2017-09-28 22:20:38" \
--m 1 \
--append

尖叫提示:使用 lastmodified 方式导入数据,要指定增量数据是要 --append(追加)还是要 --merge-key(合并)
尖叫提示:last-value 指定的值是会包含于增量导入的数据中。

2) 参数:

序号 参数 说明
1 –append 将数据追加到 HDFS 中已经存在的 DataSet 中,如果使用该参数,sqoop 会把数据先导入到临时文件目录,再合并。
2 –as-avrodatafile 将数据导入到一个 Avro 数据文件中
3 –as-sequencefile 将数据导入到一个 sequence 文件中
4 –as-textfile 将数据导入到一个普通文本文件中
5 –boundary-query < statement> 边界查询,导入的数据为该参数的值(一条sql语句)所执行的结果区间内的数据。
6 –columns < col1, col2, col3> 指定要导入的字段
7 –direct 直接导入模式,使用的是关系数据库自带的导入导出工具,以便加快导入导出过程。
8 –direct-split-size 在使用上面direct直接导入的基础上,对导入的流按字节分块,即达到该阈值就产生一个新的文件
9 –inline-lob-limit 设定大对象数据类型的最大值
10 –m或–num-mappers 启动N个 map 来并行导入数据,默认4个。
11 –query或–e < statement> 将查询结果的数据导入,使用时必须伴随参–target-dir,–hive-table,如果查询中有 where 条件,则条件后必须加上 $CONDITIONS 关键字
12 –split-by < column-name> 按照某一列来切分表的工作单元,不能与–autoreset-to-one-mapper连用(请参考官方文档)
13 –table < table-name> 关系数据库的表名
14 –target-dir < dir> 指定 HDFS 路径
15 –warehouse-dir < dir> 与14参数不能同时使用,导入数据到 HDFS 时指定的目录
16 –where 从关系数据库导入数据时的查询条件
17 –z或–compress 允许压缩
18 –compression-codec 指定 hadoop 压缩编码类,默认为 gzip(Use Hadoop codec default gzip)
19 –null-string < null-string> string 类型的列如果 null,替换为指定字符串
20 –null-non-string < null-string> 非 string 类型的列如果 null,替换为指定字符串
21 –check-column < col> 作为增量导入判断的列名
22 –incremental < mode> mode:append 或 lastmodified
23 –last-value < value> 指定某一个值,用于标记增量导入的位置

5.2.6 命令&参数:export

从 HDFS(包括Hive和HBase)中奖数据导出到关系型数据库中。
1) 命令:
如:

$ bin/sqoop export \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--export-dir /user/staff \
--input-fields-terminated-by "\t" \
--num-mappers 1

2) 参数:

序号 参数 说明
1 –direct 利用数据库自带的导入导出工具,以便于提高效率
2 –export-dir < dir> 存放数据的HDFS的源目录
3 -m或–num-mappers < n> 启动N个map来并行导入数据,默认4个
4 –table < table-name> 指定导出到哪个RDBMS中的表
5 –update-key < col-name> 对某一列的字段进行更新操作
6 –update-mode < mode> updateonly,allowinsert(默认)
7 –input-null-string < null-string> 请参考import该类似参数说明
8 –input-null-non-string < null-string> 请参考import该类似参数说明
9 –staging-table < staging-table-name> 创建一张临时表,用于存放所有事务的结果,然后将所有事务结果一次性导入到目标表中,防止错误
10 –clear-staging-table 如果第9个参数非空,则可以在导出操作执行前,清空临时事务结果表

5.2.7 命令&参数:codegen

将关系型数据库中的表映射为一个 Java 类,在该类中有各列对应的各个字段。
1) 命令:
如:

$ bin/sqoop codegen \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--bindir /home/admin/Desktop/staff \
--class-name Staff \
--fields-terminated-by "\t"

2) 参数:

序号 参数 说明
1 –bindir < dir> 指定生成的 Java 文件、编译成的 class 文件及将生成文件打包为 jar 的文件输出路径
2 –class-name < name> 设定生成的 Java 文件指定的名称
3 –outdir < dir> 生成 Java 文件存放的路径
4 –package-name < name> 包名,如 com.z,就会生成 com 和 z 两级目录
5 –input-null-non-string < null-str> 在生成的 Java 文件中,可以将 null 字符串或者不存在的字符串设置为想要设定的值(例如空字符串)
6 –input-null-string < null-str> 将null字符串替换成想要替换的值(一般与5同时使用)
7 –map-column-java < arg> 数据库字段在生成的 Java 文件中会映射成各种属性,且默认的数据类型与数据库类型保持对应关系。该参数可以改变默认类型,例如:–map-column-java id=long, name=String
8 –null-non-string < null-str> 在生成 Java 文件时,可以将不存在或者 null 的字符串设置为其他值
9 –null-string < null-str> 在生成 Java 文件时,将 null 字符串设置为其他值(一般与8同时使用)
10 –table < table-name> 对应关系数据库中的表名,生成的 Java 文件中的各个属性与该表的各个字段一一对应

5.2.8 命令&参数:create-hive-table

生成与关系数据库表结构对应的 hive 表结构。
1) 命令:
如:

$ bin/sqoop create-hive-table \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--hive-table hive_staff

2) 参数:

序号 参数 说明
1 –hive-home < dir> Hive 的安装目录,可以通过该参数覆盖掉默认的 Hive 目录
2 –hive-overwrite 覆盖掉在 Hive 表中已经存在的数据
3 –create-hive-table 默认是 false,如果目标表已经存在了,那么创建任务会失败
4 –hive-table 后面接要创建的 hive 表
5 –table 指定关系数据库的表名

5.2.9 命令&参数:eval

可以快速的使用 SQL 语句对关系型数据库进行操作,经常用于在 import 数据之前,了解一下 SQL 语句是否正确,数据是否正常,并可以将结果显示在控制台。
1) 命令:
如:

$ bin/sqoop eval \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--query "SELECT * FROM staff"

2) 参数:

序号 参数 说明
1 –query 或 –e 后跟查询的 SQL 语句

5.2.10 命令&参数:import-all-tables

可以将 RDBMS 中的所有表导入到 HDFS 中,每一个表都对应一个 HDFS 目录。
1) 命令:
如:

$ bin/sqoop import-all-tables \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--warehouse-dir /all_tables

2) 参数:

序号 参数 说明
1 –as-avrodatafile 这些参数的含义均和import对应的含义一致
2 –as-sequencefile 同上
3 –as-textfile 同上
4 –direct 同上
5 –direct-split-size < n> 同上
6 –inline-lob-limit < n> 同上
7 –m或—num-mappers < n> 同上
8 –warehouse-dir < dir> 同上
9 -z或–compress 同上
10 –compression-codec 同上

5.2.11 命令&参数:job

用来生成一个 sqoop 任务,生成后不会立即执行,需要手动执行。
1) 命令:
如:

$ bin/sqoop job \
--create myjob -- import-all-tables \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456
$ bin/sqoop job \
--list
$ bin/sqoop job \
--exec myjob

尖叫提示:注意import-all-tables 和它左边的–之间有一个空格。
尖叫提示:如果需要连接 metastore,则 –meta-connect jdbc:hsqldb:hsql://hadoop102:16000/sqoop

2) 参数:

序号 参数 说明
1 –create < job-id> 创建 job 参数
2 –delete < job-id> 删除一个 job
3 –exec < job-id> 执行一个 job
4 –help 显示 job 帮助
5 –list 显示 job 列表
6 –meta-connect < jdbc-uri> 用来连接 metastore 服务
7 –show < job-id> 显示一个 job 的信息
8 –verbose 打印命令运行时的详细信息

尖叫提示:在执行一个 job 时,如果需要手动输入数据库密码,可以做如下优化:

<property>
    <name>sqoop.metastore.client.record.password</name>
    <value>true</value>
    <description>If true, allow saved passwords in the metastore.</description>
</property>

5.2.12 命令&参数:list-databases

1) 命令:
如:

$ bin/sqoop list-databases \
--connect jdbc:mysql://hadoop102:3306/ \
--username root \
--password 123456

2) 参数:
与公用参数一样

5.2.13 命令&参数:list-tables

1) 命令:
如:

$ bin/sqoop list-tables \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456

2) 参数:
与公用参数一样

5.2.14 命令&参数:merge

将 HDFS 中不同目录下面的数据合并在一起并放入指定目录中。
数据环境:

new_staff
1   AAA male
2   BBB male
3   CCC male
4   DDD male

old_staff
1   AAA female
2   CCC female
3   BBB female
6   DDD female

尖叫提示:上边数据的列之间的分隔符应该为\t,行与行之间的分割符为\n,如果直接复制,请检查之。

1) 命令:
如:

创建JavaBean:
$ bin/sqoop codegen \
--connect jdbc:mysql://hadoop102:3306/company \
--username root \
--password 123456 \
--table staff \
--bindir /home/admin/Desktop/staff \
--class-name Staff \
--fields-terminated-by "\t"

开始合并:
$ bin/sqoop merge \
--new-data /test/new/ \
--onto /test/old/ \
--target-dir /test/merged \
--jar-file /home/admin/Desktop/staff/Staff.jar \
--class-name Staff \
--merge-key id

结果:
1   AAA    MALE
2   BBB    MALE
3   CCC    MALE
4   DDD    MALE
6   DDD    FEMALE

2) 参数:

序号 参数 说明
1 –new-data < path> HDFS 待合并的数据目录,合并后在新的数据集中保留
2 –onto < path> HDFS 合并后,重复的部分在新的数据集中被覆盖
3 –merge-key < col> 合并键,一般是主键 ID
4 –jar-file < file> 合并时引入的j ar 包,该 jar 包是通过 Codegen 工具生成的jar包
5 –class-name < class> 对应的表名或对象名,该 class 类是包含在 jar 包中的
6 –target-dir < path> 合并后的数据在 HDFS 里存放的目录

5.2.15 命令&参数:metastore

记录了 Sqoop job 的元数据信息,如果不启动该服务,那么默认 job 元数据的存储目录为 ~/.sqoop,可在 sqoop-site.xml 中修改。
1) 命令:
如:启动 sqoop 的 metastore 服务

$ bin/sqoop metastore

2) 参数:

序号 参数 说明
1 –shutdown 关闭 metastore
我的GitHub地址:https://github.com/heizemingjun
我的博客园地址:https://www.cnblogs.com/chenmingjun
我的蚂蚁笔记博客地址:https://blog.leanote.com/chenmingjun
Copyright ©2018-2019 黑泽明军
【转载文章务必保留出处和署名,谢谢!】

在sqlserver中使用事务的注意事项 - 清风徐来,水波不兴 - CSDN博客

mikel阅读(850)

来源: 在sqlserver中使用事务的注意事项 – 清风徐来,水波不兴 – CSDN博客

这两天在项目开发中遇到一些业务逻辑需要进行大量的计算和数据的一致性,因此使用到SQL事务和try catch。在项目需求中,多个业务逻辑单元分别写在对应的存储过程中,并进行事务控制,同时需要一个总调用的存储过程pro_contry,这个总调用de 存储过程pro_contry通过事务封装上面的所有业务逻辑单元存储过程,当其中任何一个存储过程出现错误时,全部回滚。pro_contry调用过程中发现同时有事务嵌套,又有try catch嵌套。在测试的过程中发现各种离奇的错误现记录如下,

第一个错误:

错误描述:错误号:      3930, 错误严重级别:        16, 错位状态:         1, 错误存储过程和触发器名称:PRO_A_LogicUnit, 错误行号:       150, 错误实际信息:当前事务无法提交,而且无法支持写入日志文件的操作。请回滚该事务。

错误原因:由于pro_contry 和PRO_A_LogicUnit 中同时使用了try catch捕获错误。

解决方法:将子存储过程PRO_A_LogicUnit的try catch取消,将错误由上一级抛出处理

 

第二个错误

SAVE tran @tranName
EXEC Pro_Score_CountEverySubjectStandardRate 130
错误描述:当前事务无法提交,而且无法回滚到保存点。请回滚整个事务。

错误原因:由于在pro_contry和PRO_A_LogicUnit同时有事务处理,当PRO_A_LogicUnit中出现错误回滚 进行rollback,事务保存点设置错误导致。

解决方法:应该先判断是否已经存在事务,若已经存在则设置事务保存点,不存在创建事务处理

DECLARE @tranCounter INT

DECLARE @tranName VARCHAR(20)

SET @tranCounter = @@TRANCOUNT

SET @tranName = ‘tran’

IF @tranCounter = 0

BEGIN

BEGIN TRAN @tranName

END

ELSE

BEGIN

SAVE TRAN @tranName

END
第三个错误
在内部嵌套事务 ROLLBACK tran

错误描述: 错误号:       266, 错误严重级别:        16, 错位状态:         2, 错误存储过程和触发器名称:PRO_A_LogicUnit, 错误行号:         0, 错误实际信息:EXECUTE 后的事务计数指示 BEGIN 和 COMMIT 语句的数目不匹配。上一计数 = 1,当前计数 = 0。

错误原因:在事务中begin tran 后@@tranCount 会加1,当commit tran 后会减1,而rollback tran后 @@tranCount = 0,因此在事务嵌套中必须保存begin tran几次对应的commit tran 也几次

第三个错误
错误描述:

嵌套事务中指定 ROLLBACK tran @tranName

错误号:      6401, 错误严重级别:        16, 错位状态:         1, 错误存储过程和触发器名称:Pro_Score_CountEverySubjectStandardRate, 错误行号:       148, 错误实际信息:无法回滚 countEverySubjectStandardRate。找不到该名称的事务或保存点。

不要使用嵌套事务
不能过分使用嵌套事务,非常麻烦

当SET XACT_ABORT ON 后try catch 中遇到程序错误时catch 会事务回滚

使用save tran 替代嵌套tran

DECLARE @TranCounter INT;
SET @TranCounter = @@TRANCOUNT;

–当只有一个事务的时候进行回滚,否则嵌套事务由外面的rollback进行回滚

http://hi.baidu.com/duobaiduodu/item/79375ed7b0d60ac71a72b4f6

http://msdn.microsoft.com/zh-cn/library/ms189797.aspx

http://msdn.microsoft.com/zh-cn/library/ms175976.aspx

http://msdn.microsoft.com/zh-cn/library/ms179296%28v=SQL.100%29.aspx

http://wenku.baidu.com/view/8d1d3ded6294dd88d0d26bd0.html

http://msdn.microsoft.com/en-us/library/ms179296%28v=SQL.105%29.aspx

http://blog.csdn.net/wufeng4552/article/details/6317515

http://blog.sina.com.cn/s/blog_496cf0e70100i0em.html

http://blog.csdn.net/xmzhaoym/article/details/5120372

http://www.cnblogs.com/yangpei/archive/2010/10/07/1894408.html

sqlserver中的循环遍历(普通循环和游标循环) - 小小邪 - 博客园

mikel阅读(2183)

来源: sqlserver中的循环遍历(普通循环和游标循环) – 小小邪 – 博客园

SQL 经常用到循环,下面介绍一下普通循环和游标循环

1、首先需要一个测试表数据Student

2、普通循环

1)循环5次来修改学生表信息

–循环遍历修改记录–
declare @i int
set @i=0
while @i<5
begin
update Student set demo = @i+5 where Uid=@i
set @i=@i +1
end
–查看结果–
select * from Student

2)执行后的查询结果

3、游标循环(没有事务)

1)根据学生表实际数据循环修改信息
—游标循环遍历–
begin
declare @a int,@error int
declare @temp varchar(50)
set @a=1
set @error=0
–申明游标为Uid
declare order_cursor cursor
for (select [Uid] from Student)
–打开游标–
open order_cursor
–开始循环游标变量–
fetch next from order_cursor into @temp
while @@FETCH_STATUS = 0    –返回被 FETCH语句执行的最后游标的状态–
begin
update Student set Age=15+@a,demo=@a where Uid=@temp
set @a=@a+1
set @error= @error + @@ERROR   –记录每次运行SQL后是否正确,0正确
fetch next from order_cursor into @temp   –转到下一个游标,没有会死循环
end
close order_cursor  –关闭游标
deallocate order_cursor   –释放游标
end
go
–查看结果–
select * from Student

2)执行后的查询结果

4、游标循环(事务)

1)根据实际循环学生表信息

—游标循环遍历–
begin
declare @a int,@error int
declare @temp varchar(50)
set @a=1
set @error=0
begin tran  –申明事务
–申明游标为Uid
declare order_cursor cursor
for (select [Uid] from Student)
–打开游标–
open order_cursor
–开始循环游标变量–
fetch next from order_cursor into @temp
while @@FETCH_STATUS = 0    –返回被 FETCH语句执行的最后游标的状态–
begin
update Student set Age=20+@a,demo=@a where Uid=@temp
set @a=@a+1
set @error= @error + @@ERROR   –记录每次运行SQL后是否正确,0正确
fetch next from order_cursor into @temp   –转到下一个游标
end
if @error=0
begin
commit tran   –提交事务
end
else
begin
rollback tran –回滚事务
end
close order_cursor  –关闭游标
deallocate order_cursor   –释放游标
end
go
–查看结果–
select * from Student

2)执行后的查询结果:

平时多记记,到用时才能看看,记录你的进步,分享你的成果