Hive(四):c#通过odbc访问hive

时间:2022-02-03 03:11:46

hive odbc 驱动配置成功后,通过c#访问就变得比较简单了,分为查询与更新操作,直接附上测试代码。在此过程中需要注意c#工程编译的目标平台

  • 读写访问代码示例:
    public class HiveOdbcClient
    {
    /// <summary>
    ///
    /// </summary>
    public static HiveOdbcClient Current
    {
    get { return new HiveOdbcClient(); }
    } /// <summary>
    ///
    /// </summary>
    /// <param name="context"></param>
    public void ExcuteNoQuery(string dns, string sql)
    {
    OdbcConnection conn = null; try
    {
    conn = new OdbcConnection(dns);
    conn.Open();
    OdbcCommand cmd = new OdbcCommand(sql, conn);
    cmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
    throw ex;
    }
    finally
    {
    if (null != conn)
    {
    conn.Close();
    }
    }
    } /// <summary>
    ///
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public DataSet Query(string dns, string sql,string tblName = "tbl")
    {
    DataSet set = new DataSet();
    OdbcConnection conn = null; try
    {
    conn = new OdbcConnection(dns);
    conn.Open();
    OdbcCommand cmd = conn.CreateCommand();
    cmd.CommandText = sql;
    OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);
    adapter.Fill(set, tblName);
    }
    catch (Exception ex)
    {
    throw ex;
    }
    finally
    {
    if (null != conn)
    {
    conn.Close();
    }
    } return set;
    }
    }
  • 测试:新建一个控制台工程,测试表创建及数据插入,示例代码如下:
    class Program
    { static void Main(string[] args)
    {
    Console.WriteLine("按任意键开始进行建表及数据插入测试");
    Console.ReadKey(); string dns = "DSN=myhive;UID=hive;PWD="; string sql = "create table Employee(ID string,Code string,Name string)";
    HiveOdbcClient.Current.ExcuteNoQuery(dns,sql); sql = "insert into table Employee values('002','002','zhangShan');";
    HiveOdbcClient.Current.ExcuteNoQuery(dns, sql); Console.WriteLine("数据插入完成,按任意键退出");
    Console.ReadKey();
    } }
  • 使用上一章介绍的SQurriel 工具,执行: Select * from employee  ,显示代码中插入的数据则OK