您好,欢迎访问一九零五行业门户网

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

最近在写一个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.state为open状态下操作,因为架构设计原因我拒绝这种野蛮方式,最后确定使用正则表达式进行动态替换,翻了下资料写出如下regx:
(?
注:如果在c#中,请将上述表达式中的双引号()写双份,以进行字符转义。
好吧,下面给出该方法的完整代码(c#):
1: ///
2: /// 修复连接字符串,将数据库文件相对路径的转换为绝对路径。
3: ///
4: /// 连接字符串的值。
5: /// 返回被修整过的连接字符串,如果无需修整则返回参数原值。
6: private static string fixconnectionstring(string connectionstring)
7: {
8: const string datasource_pattern = @(?]*\s*)\w+[^;']+(?=\b);
9: 
10: if(string.isnullorempty(connectionstring))
11: return connectionstring;
12: 
13: match match = regex.match(connectionstring, datasource_pattern, regexoptions.ignorecase | regexoptions.singleline);
14: if(!match.success)
15: return connectionstring;
16: 
17: if(path.ispathrooted(match.value))
18: return connectionstring;
19: 
20: string directoryname = path.getdirectoryname(assembly.getexecutingassembly().getname().codebase);
21: string datasource = path.combine(directoryname, match.value);
22: 
23: return regex.replace(connectionstring, datasource_pattern, datasource, regexoptions.ignorecase | regexoptions.singleline);
24: }
其它类似信息

推荐信息