Home  >  Article  >  Database  >  数据库连接字符串解析的正则表达式

数据库连接字符串解析的正则表达式

WBOY
WBOYOriginal
2016-06-07 15:06:091678browse

最近在写一个Windows Mobile的小程序,其中需要访问数据库,数据库连接字符串大致如下: Data Source=Zongsoft.MAS.sdf;Password=xxxxxx;Persist Security Info=True 其中的 Data Source 部分指定了数据库文件的名称,但是当使用 DbConnection.Open() 方法进

最近在写一个Windows Mobile的小程序,其中需要访问数据库,数据库连接字符串大致如下:

Data Source=Zongsoft.MAS.sdf;Password=xxxxxx;Persist Security Info=True

其中的Data Source部分指定了数据库文件的名称,但是当使用DbConnection.Open()方法进行连接时提示找不到数据库文件,经查实发现其必须指定为数据库文件的完整路径。——这是个麻烦事,因为手机程序部署的物理位置并不能确定,故此无法在配置文件中指定数据库文件的完整路径

首先,我想到用DbConnectionStringBuilder来动态生成连接字符串,但是,在.NET CompactFramework 3.5中并不支持该类。退而其次发现可以使用DbConnection.ChangeDatabase()方法来修改数据库路径,但是,经调试发现该方法只能在DbConnection.StateOpen状态下操作,因为架构设计原因我拒绝这种野蛮方式,最后确定使用正则表达式进行动态替换,翻了下资料写出如下Regx:

(?

注:如果在C#中,请将上述表达式中的双引号(")写双份,以进行字符转义。

 

好吧,下面给出该方法的完整代码(C#):

<span>   1:</span> <span>/// <summary></summary></span>
<span>   2:</span> <span>/// 修复连接字符串,将数据库文件相对路径的转换为绝对路径。</span>
<span>   3:</span> <span>/// </span>
<span>   4:</span> <span>/// <param name="connectionString">连接字符串的值。</span>
<span>   5:</span> <span>/// <returns>返回被修整过的连接字符串,如果无需修整则返回参数原值。</returns></span>
<span>   6:</span> <span>private</span> <span>static</span> <span>string</span> FixConnectionString(<span>string</span> connectionString)
<span>   7:</span> {
<span>   8:</span>     <span>const</span> <span>string</span> DATASOURCE_PATTERN = <span>@"(?<span>"]*\s*)\w+[^;'"</span><span>"]+(?=\b)"</span>;</span>
<span>   9:</span>  
<span>  10:</span>     <span>if</span>(<span>string</span>.IsNullOrEmpty(connectionString))
<span>  11:</span>         <span>return</span> connectionString;
<span>  12:</span>  
<span>  13:</span>     Match match = Regex.Match(connectionString, DATASOURCE_PATTERN, RegexOptions.IgnoreCase | RegexOptions.Singleline);
<span>  14:</span>     <span>if</span>(!match.Success)
<span>  15:</span>         <span>return</span> connectionString;
<span>  16:</span>  
<span>  17:</span>     <span>if</span>(Path.IsPathRooted(match.Value))
<span>  18:</span>         <span>return</span> connectionString;
<span>  19:</span>  
<span>  20:</span>     <span>string</span> directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
<span>  21:</span>     <span>string</span> dataSource = Path.Combine(directoryName, match.Value);
<span>  22:</span>  
<span>  23:</span>     <span>return</span> Regex.Replace(connectionString, DATASOURCE_PATTERN, dataSource, RegexOptions.IgnoreCase | RegexOptions.Singleline);
<span>  24:</span> }
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn