[英]How do I run SQL code using c# 3.5?
I have an HTML textbox that contains some SQL code that I need executed. 我有一个HTML文本框,其中包含一些需要执行的SQL代码。 I am able to retrieve the actual code from the textbox but I am not sure how to go about executing the code.
我可以从文本框中检索实际的代码,但是我不确定如何执行代码。 Any simple and elegant ways using c# 3.5?
使用c#3.5有任何简单而优雅的方法吗?
DON'T EXECUTE CODE FROM A TEXTBOX 不要从文本框中执行代码
unless you really trust what is being entered. 除非您真的相信输入的内容。
If you do, use this: 如果这样做,请使用以下命令:
SqlConnection con = new SqlConnection("Your connection string");
con.Open();
SqlCommand cmd = new SqlCommand(TexdtBox1.Text, con);
cmd.ExecuteNonQuery();
con.Close()
Note that this will not return anything, jsut run the query. 注意,这不会返回任何内容,jsut运行查询。 If you want to return data, you need a SqlDataAdaptor or SqlDataReader.
如果要返回数据,则需要SqlDataAdaptor或SqlDataReader。
It depends on the type of database you want to execute it against. 这取决于您要对其执行数据库的类型。 If I can assume you want to talk to a SQL Server database, look at the following classes:
如果我可以假设您想与SQL Server数据库进行对话,请查看以下类:
从文本框中使用CommandText创建SqlCommand 。
here's a little (untested untested because typed right in the SO textbox) sample code: 这是一些示例代码(未经测试,未经测试,因为在SO文本框中键入了正确的代码):
using System.Data;
namespace MyGreatNamespace
{
class MyGreatClass
{
static public DataTable executeTable( string query )
{
return executeTable( query, null, null );
}
static public DataTable executeTable( string query, string[] params, object[] values )
{
DataTable myTable = new DataTable();
using ( SqlConnection connection = new SqlConnection( myConnectionString ) )
using( SqlCommand command = new SqlCommand( connection ) )
{
command.CommandType = CommandType.Text;
command.CommandText = myQuery;
if ( parameters.Count == values.Count && parameters.Count > 0 )
{
for( int i = 0; i < parameters.Count; i ++ )
{
command.addParameterWithValue( parameters[i], values[i] );
}
}
using( SqlDataAdapter adapter = new SqlDataAdapter( command ) )
{
adapter.Fill( out myTable );
}
}
return myTable;
}
}
}
我不建议这样做,但如果这样做,至少要验证输入的SQL以SELECT开头,并且不包含任何分号(;)或注释字符(-和/ *)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.