csharp: read system DSN configured get Driver Names on windows
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Data.Odbc; namespace SQLanyWhereDemo
{
public partial class Form5 : Form
{ [DllImport("odbc32")]
public static extern short SQLAllocHandle(short HandleType, IntPtr InputHandle, out IntPtr OutputHandle);
[DllImport("odbc32", CharSet = CharSet.Unicode)]
public static extern short SQLSetEnvAttr(IntPtr envHandle, ushort attribute, IntPtr val, int stringLength);
[DllImport("odbc32.dll", CharSet = CharSet.Ansi)]
public static extern short SQLDataSources(IntPtr EnvironmentHandle, ushort Direction, StringBuilder ServerName, short BufferLength1, ref short NameLength1Ptr, StringBuilder Description, short BufferLength2, ref short NameLength2Ptr);
[DllImport("ODBCCP32.dll")]
private static extern bool SQLConfigDataSource(IntPtr parent, int request, string driver, string attributes); [DllImport("odbccp32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool SQLGetInstalledDriversW(char[] lpszBuf, ushort cbufMax, out ushort pcbBufOut); public const int SQL_SUCCESS = 0;
public const int SQL_ERROR = -1; public const int SQL_FETCH_NEXT = 1;
public const int SQL_FETCH_FIRST = 2;
public const int SQL_FETCH_FIRST_USER = 31;
public const int SQL_FETCH_FIRST_SYSTEM = 32; public const int SQL_ATTR_ODBC_VERSION = 200; public const int SQL_HANDLE_ENV = 1;
public const int SQL_HANDLE_DBC = 2;
public const int SQL_HANDLE_STMT = 3;
public const int SQL_HANDLE_DESC = 4;
/// <summary>
///
/// </summary>
public Form5()
{
InitializeComponent();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{ List<ODBCStr> ls = new List<ODBCStr>();
short iResult = 0;
IntPtr lhEnvIn = (IntPtr)0;
IntPtr lhEnv = (IntPtr)0;
StringBuilder sDSNItem = new StringBuilder(1024);
StringBuilder sDRVItem = new StringBuilder(1024);
short iDSNLen = 0;
short iDRVLen = 0; SQLSetEnvAttr(lhEnv, 200, (IntPtr)3, 0); iResult = SQLAllocHandle(1, lhEnvIn, out lhEnv);
MessageBox.Show(iResult.ToString(), "iResult SQLAllocHandle"); //short iResult = 0;
//IntPtr lhEnvIn = (IntPtr)0;
//IntPtr lhEnv = (IntPtr)0;
//StringBuilder sDSNItem = new StringBuilder(1024);
//StringBuilder sDRVItem = new StringBuilder(1024);
//short iDSNLen = 0;
//short iDRVLen = 0; iResult = SQLAllocHandle(SQL_HANDLE_ENV, lhEnvIn, out lhEnv); SQLSetEnvAttr(lhEnv, SQL_ATTR_ODBC_VERSION, (IntPtr)3, 0); if (iResult == SQL_SUCCESS)
{
ODBCStr sr = null;
iResult = SQLDataSources(lhEnv, SQL_FETCH_FIRST, sDSNItem, 1024, ref iDSNLen, sDRVItem, 1024, ref iDRVLen);
while (iResult == SQL_SUCCESS)
{
sr=new ODBCStr();
//MessageBox.Show(sDSNItem.ToString(), "sDSNItem.ToString()");
iResult = SQLDataSources(lhEnv, SQL_FETCH_NEXT, sDSNItem, 1024, ref iDSNLen, sDRVItem, 1024, ref iDRVLen);
sr.DsnName = sDSNItem.ToString();
sr.DriveName = sDRVItem.ToString();
//string str = "SERVER=HOME\0DSN=MYDSN\0DESCRIPTION=MYDSNDESC\0DATABASE=DBServer\0TRUSTED_CONNECTION=YES";
//SQLConfigDataSource((IntPtr)0, 4, "Sybase SQL Anywhere 5.0", str);//SQL Server
//MessageBox.Show(str); ls.Add(sr);
}
} this.dataGridView1.DataSource = ls; }
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{ string[] list = GetOdbcDriverNames(); } /// <summary>
/// Gets the ODBC driver names from the SQLGetInstalledDrivers function.
/// </summary>
/// <returns>a string array containing the ODBC driver names, if the call to SQLGetInstalledDrivers was successfull; null, otherwise.</returns>
public static string[] GetOdbcDriverNames()
{
string[] odbcDriverNames = null;
char[] driverNamesBuffer = new char[ushort.MaxValue];
ushort size; bool succeeded = SQLGetInstalledDriversW(driverNamesBuffer, ushort.MaxValue, out size); if (succeeded == true)
{
char[] driverNames = new char[size - 1];
Array.Copy(driverNamesBuffer, driverNames, size - 1);
odbcDriverNames = (new string(driverNames)).Split('\0');
} return odbcDriverNames;
}
} /// <summary>
/// 涂聚文
/// 20180223
/// Geovin Du
/// </summary>
public class ODBCStr
{
/// <summary>
///
/// </summary>
public string DriveName { get; set; }
/// <summary>
///
/// </summary>
public string DsnName { get; set; }
/// <summary>
///
/// </summary>
public string ServerName { get; set; }
/// <summary>
///
/// </summary>
public string DatabaseName { get; set; }
/// <summary>
///
/// </summary>
public string DataSrource { get; set; }
/// <summary>
///
/// </summary>
public string DataFile { get; set; } } }
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{ //string connectionString = "dsn=LocalServer";
//System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
//builder.ConnectionString = connectionString;
//string server = builder["Data Source"] as string;
//string database = builder["Initial Catalog"] as string; //string conString = "SERVER=localhost;DATABASE=tree;UID=root;PASSWORD=branch;Min Pool Size = 0;Max Pool Size=200";
//SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(conString);
//string user = builder.UserID;
//string pass = builder.Password; //OdbcConnectionStringBuilder buil =new OdbcConnectionStringBuilder();
//buil.Driver = "Sybase SQL Anywhere 5.0";
//buil.Dsn = "achive"; System.Data.Odbc.OdbcConnectionStringBuilder connBuilder = new System.Data.Odbc.OdbcConnectionStringBuilder();
connBuilder.Dsn = "achive";
connBuilder.Driver = "Sybase SQL Anywhere 5.0";
//connBuilder.Add("uid", "");
//connBuilder.Add("pwd", ""); connBuilder.Add("database", "涂聚文"); string sss = connBuilder.ToString();
//MessageBox.Show(connBuilder.ToString());
System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection(connBuilder.ToString());
try
{
conn.Open();
System.Data.Odbc.OdbcCommand comm = new System.Data.Odbc.OdbcCommand("select count(*) from item_description", conn);
var reader = comm.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader[0].ToString());
}
MessageBox.Show("连接成功!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
conn.Close();
} //设置
//OdbcConnectionStringBuilder.Dsn=connectionString; } /// <summary>
///
/// </summary>
/// <param name="Database"></param>
/// <param name="Version"></param>
/// <returns></returns>
public static string GetODBCDriverName(string Database, string Version)
{ string ODBCDriverName = ""; RegistryKey registryKey = Registry.LocalMachine; RegistryKey registrySubKey = registryKey.OpenSubKey(@"SOFTWARE\ODBC\ODBCINST.INI\"); String[] SubKeyNames = registrySubKey.GetSubKeyNames(); foreach (String KeyName in SubKeyNames)
{ if (KeyName.Contains(Database) && KeyName.Contains(Version))
{ ODBCDriverName = KeyName; break; }
} registrySubKey.Close(); registryKey.Close(); return ODBCDriverName; }
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
OdbcConnectionStringBuilder odbcConnectionStringBuilder = new OdbcConnectionStringBuilder();
OdbcCommand odbcCommand;
int RecordFound = 0;
odbcConnectionStringBuilder.Driver = GetODBCDriverName("Sybase SQL Anywhere", "5.0");
if (odbcConnectionStringBuilder.Driver == "")
{ MessageBox.Show(" ODBC Driver is not installed");
//return -1;
}
odbcConnectionStringBuilder.Add("DSN", "achive");
//odbcConnectionStringBuilder.Add("UID", "no-user");
//odbcConnectionStringBuilder.Add("PWD", "no-pass");
odbcConnectionStringBuilder.Add("DB", @"C:\Documents and Settings\geovindu\My Documents\Visual Studio 2010\Projects\SQLanyWhereDemo\SQLanyWhereDemo\bin\Debug\geovindu.db;"); // copy of database SPORTS
odbcConnectionStringBuilder.Add("HOST", ".");
//odbcConnectionStringBuilder.Add("PORT", "5162"); // i found this port inn the log file
using (OdbcConnection connection = new OdbcConnection(odbcConnectionStringBuilder.ConnectionString)) { connection.Open();
try
{
odbcCommand = new OdbcCommand("SELECT COUNT(*) FROM pub.Invoice WHERE Invoicenum > 0", connection);
odbcCommand.CommandTimeout = 1;
object executeScalarResult = odbcCommand.ExecuteScalar();
RecordFound = Convert.ToInt32(executeScalarResult);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
} }
csharp: read system DSN configured get Driver Names on windows的更多相关文章
- How to configure ODBC DSN to access local DB2 for Windows
How to configure ODBC DSN to access local DB2 for Windows MA Genfeng (GuangdongUnitoll Services inco ...
- busdog is a filter driver for MS Windows (XP and above) to sniff USB traffic.
https://code.google.com/p/busdog/ busdog is a filter driver for MS Windows (XP and above) to sniff U ...
- UAP开发错误之The given System.Uri cannot be converted into a Windows.Foundation.Uri(windows phone背景更换)
今天博主在开发一款windows phone应用时,希望实现app背景的更换,思路很简单.使用ApplicationDataContainer容器存储我的图片路径,每次载入应用时读取这个路径以决定我用 ...
- mongodb c++ driver(2.53)windows编译
编译环境: (1) 下载python2.7, 使用x86_32位,因为scons只有32位安装包可用: (2) 下载scons2.3.0,The current production release ...
- MongoDB C Driver Building on Windows
一.编译mongodb c driver: 需要先安装OpenSSL:(参见:http://bbs.aircheng.com/read-2222-1) 步骤:(MongoDB步) 1.下载Active ...
- System Operations on AWS - Lab 4W - Monitoring (Windows)
创建Web Server实例,配置CloudWatch来收集Web Server的系统日志,当错误登录次数达到设定值时触发报警 1. 创建Web Server 1.1 创建一个IAM策略 1.2 创建 ...
- Fail to start neutron-server
问题: [root@localhost ~]# systemctl status neutron-server ● neutron-server.service - OpenStack Neutron ...
- openstack学习之neutron ml2初始化代码分析
这里没有 去详细考虑neutron server怎么初始化的,而是直接从加载插件的地方开始分析.首先我们看下下面这个文件. Neutron/api/v2/router.py class APIRout ...
- System Error Codes
很明显,以下的文字来自微软MSDN 链接http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx M ...
随机推荐
- 3.装配Bean 基于XML
一.实例化方式 3种bean实例化方式:默认构造.静态工厂.实例工厂 1.默认构造 <bean id="" class=""> 必须提供默认构造 2 ...
- issue:ssh自动断开
使用ssh连接云服务器的时候,几分钟不操作terminal就会卡住,实际上ssh连接已经断开了,感觉很不爽.(可能云服务器供应商在系统中做了设置) 解决办法: step1:vim /etc/ssh/s ...
- Yii2 三层设计模式:SQL Command、Query builder、Active Record(ORM)
用Yii2也有一段时间了,发现Yii2 Framework对Database的操作有非常良好的结构和弹性. 接下来介绍三种数据库操作方式. SQL Command Level: // Get DB c ...
- 锚接口(下)——html5的history api
概述 虽然html5的history api是H5专门用来解决记录历史记录和单页面的方法,但是很多老式的浏览器并不支持它,所以一般遇到老式的浏览器会做一个polyfill使用之前的hashchange ...
- 解决element-ui upload组件报错 Avoid using non-primitive value as key, use string/number value instead
到底是啥错呢,就是要求你的key必须是string或者number类型 那么解决就是找到这个报错的key(在node_modules/element-ui/lib/element-ui.common. ...
- 【Spark调优】Shuffle原理理解与参数调优
[生产实践经验] 生产实践中的切身体会是:影响Spark性能的大BOSS就是shuffle,抓住并解决shuffle这个主要原因,事半功倍. [Shuffle原理学习笔记] 1.未经优化的HashSh ...
- 从 moment -> nodejs -> sequelize -> postgres,你都得设置好时区
背景 最近在做报表统计,因为 sequelize 的时区配置没加导致了统计数字对不上的问题. 问:大家都知道时区,但是你清楚 UTC 和 GMT 的区别吗? 答:UTC 是我们现在用的时间标准,GMT ...
- C# TableLayoutPanel使用方法
一.利用TableLayoutPanel类展示表格,以10行5列为例 第1步:在前台创建一个panel,使TableLayoutPanel对象填充其内部. 第2步:创建TableLayoutPanel ...
- gulp和grunt 分享ppt
gulp是前端开发过程中对代码进行构建的工具,是自动化项目的构建利器:她不仅能对网站资源进行优化,而且在开发过程中很多重复的任务能够使用正确的工具自动完成:使用她,我们不仅可以很愉快的编写代码,而且大 ...
- jq通过对象获取其ID值
$(this).click(function(){ var this_id=$(this).attr("id");// attr(属性名) 获取属性的值 alert(this_id ...