将参数传递给sql脚本
问题描述:
现在,我可以通过HTTPpost方法从我的网站执行脚本。将参数传递给sql脚本
string scriptDirectory = "c:\\Users\\user\\Documents";
string sqlConnectionString = "Integrated Security=SSPI;" +
"Persist Security Info=True;Data Source=ARES";
DirectoryInfo di = new DirectoryInfo(scriptDirectory);
FileInfo[] rgFiles = di.GetFiles("*.sql");
foreach (FileInfo fi in rgFiles)
{
FileInfo fileInfo = new FileInfo(fi.FullName);
string script = fileInfo.OpenText().ReadToEnd();
SqlConnection connection = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(connection));
server.ConnectionContext.ExecuteNonQuery(script);
connection.Close();
}
Atm脚本正在创建一个新的数据库(数据库不是动态的)。我想传入网站用户输入的参数,然后将其传递到sql脚本中。基本上我希望他们选择要创建的数据库的名称。
SQL命令的正确位置在脚本的开头。
CREATE DATABASE [This is where the name will be passed to]
GO
USE[This is where the name will be passed to]
编辑:
我有这样的代码
SqlCommand createDbCommand = new SqlCommand();
createDbCommand.CommandText = "CREATE DATABASE [@DataBase]";
createDbCommand.Parameters.Add("@DataBase", SqlDbType.Text);
createDbCommand.Parameters["@DataBase"].Value = client.HostName;
我必须手动现在进入我的脚本的顶部呢?
答
创建一个新的SqlCommand并将脚本CommandText
设置为您的脚本文本,然后使用cmd.Parameters.Add
设置参数。
使用参数与CRUD操作是很简单的(谷歌为“T-SQL参数”千资源的),但是参数化的类型名称是更多地参与,对于有一个漫长的MSDN文章在这里:http://msdn.microsoft.com/en-us/library/bb510489.aspx
如果你正在寻找快速'n'脏的东西,你可以通过在你的sql文件中放置替换序列并使用正则表达式来进行每个替换,例如使用语法“{{fieldName}}
”来推出自己的参数化系统。
您能举一个关于如何使用Parameters.Add的例子,具体来说就是您将作为展示位置持有者输入到脚本中的内容。 – zms6445 2013-03-08 21:31:54
我已经更新了我的答案。 – Dai 2013-03-08 21:38:09
我已经添加了一些代码。我只需要知道除了打开文件并手动修改文件以输入该命令之外,是否还有其他方法。 – zms6445 2013-03-08 21:38:16